Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

initialising and freeing matrix

Status
Not open for further replies.

ggc01r

Programmer
Aug 13, 2002
1
GB
Hi,

I need to create and eventually destroy a (square) 2-D array of ints; the way I am creating it is:

Code:
int **matrix;
matrix=(int **)calloc(sizeof(int *) * NUM_ENTRIES, sizeof(int *));
for(i=0; i<NUM_ENTRIES; i++)
	matrix[i]=(int *)calloc(sizeof(int) * NUM_ENTRIES, sizeof(int));

I'm using calloc instead of malloc because it's useful to have all the elements initialised to 0. Firstly, is this the best way to do it (NUM_ENTRIES will be about 80,000)? Secondly, how do you free up all the memory taken up by the matrix?

thanks very much for any help.
Graham.
 
I believe that this code does not exactly do what you want it to do.

Calloc takes as first argument how many elements you want to alloc space for and as second how large each such element is. As you have written, you allocate sizeof(int*) * sizeof(int*) * NUM_ENTRIES bytes of space when all you need is sizeof(int*) * NUM_ENTRIES. What you should write there is

matrix = (int **)calloc(NUM_ENTRIES, sizeof(int *));

and the second calloc would be

matrix = (int *)calloc(NUM_ENTRIES, sizeof(int));

To dealloc this later you simply do the corresponding free:s but in reverse order, go through the matrix and free what that pointer points to and then free matrix. Like this:

for (i = 0; i < NUM_ENTRIES; i++) {
/* make sure that the pointer points to something */
if (matrix != NULL) {
free(matrix);
}
}
free(matrix);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top