We can allocate memory for 2d matrix using 1 malloc call as
int (*a)[5];
int i,j;
a=malloc(sizeof(int*) * 5); //allocating 5 pointers
and each pointer points to an array of 5 ints
How can we free this memory allocated successfully?
Using free(a) gives run-time error
Using
for(i=0;i<5;i++)
free(a[i]);
free(a);
This also gives run-time error
Edit: THE WHOLE STORY.
Previously I ignored THREE other ways to allocate 2d arrays.
Dynamic 2d array method 1:
This one works if you know the the number of columns at compile time.
This works because m is declared as a pointer to an array of CCOLS ints. The compiler knows its size and does the math for you. m[iRow] = an array of CCOLS ints.
You can only pass this to functions with this signature:
and maybe this signature, depending upon your compiler and the switches you use:
not this signature:
Since the memory layouts and sizes are different.
int m[][CCOLS] looks like this:
int **m looks like this:
Dynamic 2d array method 2 (C99 which is not supported by all compilers):
This one is the same as the previous but you don’t need to know dimensions at compile time.
You can only pass this to functions with this signature:
or this one
If you use gcc, here is more info.
Dynamic 2d array method 3 using the STACK! (C99 which is not supported by all compilers):
This lets you avoid malloc entirely if you are ok with your 2d array on the stack.
I assume you could declare a global variable this way too.
You pass this to functions the same way as method 2.
Dynamic 2d array method 4:
This is the array of pointers method that a lot of people use.
You use one malloc to allocate to be efficient. And of course you then only use one free. Only if you have HUGE arrays where contiguous memory becomes and issue, would you want to malloc each row individually.