Reputation: 1976
I use Visual C++ 2010 and I'm trying to use free() with two dimensional array:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 8
int main(){
int **matrix = (int**)malloc(sizeof(int*)*SIZE);
int i;
for(i=0; i<SIZE; i++){
matrix[i] = (int*)malloc(sizeof(int)*SIZE);
}
for(i=0; i<SIZE; i++){
free(matrix[i]);
}
free(matrix);
getch();
return 0;
}
Am I doing this right?
Regards.
Upvotes: 1
Views: 155
Reputation: 39194
Basically it should be right.
Btw you don't need to call malloc
for each row of the 2d array you are trying to allocate (unless you have specific reasons to do that).
You can use just one malloc
and one free
:
malloc(sizeof(int*)*ROW_NUM * COL_NUM);
Using a single call to malloc
has also the benefits to allocate continuosly in memory the elements of your matrix.
Upvotes: 7