Search code examples
carraysfree

Why is this showing me an error when I try to free a matrix?


When i try to compile my code , I get this error and I don't know why:

error: incompatible type for argument 1 of ‘free’ free(A[i]);

void freeMatrix(int N, double *A)
{
for(int i = 0; i < N; i++)
        free(A[i]);
free(A);
}

Solution

  • Not enough reputation to comment, hence writing as an answer.

    A[i] is of type double. free() expects a pointer. did you perhaps mean to declare the function as

    void freeMatrix(int N, double **A){
       for(int i = 0; i < N; i++)
          free(A[i]);
       free(A);
    }
    

    The question was clarified: the matrix was originally created as

    double *A = (double *)malloc(N * N * sizeof(double));
    

    In this case, a single call

    free(A);
    

    is enough. In general, you should call free() exactly as often as malloc()