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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to free memory allocated to a multidimensional array

Status
Not open for further replies.

taykin

Programmer
Jun 27, 2003
1
US
Hi,

How can I free the memory allocated dynamically to an array as follows. I can't find any reference to the use of "free" for this type dynamic allocation. Thank you.

t_shift_table = (int ***)malloc(num_shift_type*sizeof(int**));
for(i=0;i<num_shift_type;++i){
kk = nshifts;
t_shift_table = (int **)malloc(kk*sizeof(int*));

for(j=0;j<nshifts;++j){
t_shift_table[j] = (int *)malloc(tour_length*sizeof(int));
}
}



Regards,

Taykin
 
Nothing special about this :
You use malloc to allocate memory, so you will have to use free to release the memory again.
The argument to free are the pointers obtained via malloc - only you have to do it the other way round.

/JOlesen
 
Initially your code looks like it is allocating a 3D array, reading further your code handles it like a 2D.
In that case, if t_shift_table is a int ***, the two t_shift_table occurences inside the loops, should be preceded by a *, like *t_shift_table.
Further, bringing 'kk = nshifts;' outside the main loop prevents your code to re-assign the same thing to kk every loop.

Here are two little functions. I haven't tested if it works and didn't provide error checking; that's up to you, . But syntactically they're ok.

Code:
//Somewhere in code is declared
long    height=480;
long    width=640;
long**  array2d;

//The array must be allocated and freed;
//so two functions are constructed:

//Function to allocate 2D (long) array
void malloc_array2d(long*** pArray2d, long height, long width)
{
	long i=0;

	*pArray2d = (long **)malloc(sizeof(long *) * height);

	while(i < height)

		*pArray2d[i++] = (long *)malloc(sizeof(long) * width);
}

//Function to free 2D (long) array
void free_array2d(long*** pArray2d, long height)
{
	long i=0;

	while(i < height){

		free(*pArray2d[i]);

		i++;
	}

	free(*pArray2d);
	*pArray2d = NULL;
}

//To allocate the array call...
malloc_array2d(&array2d, height, width);

//To free the array call...
free_array2d(&array2d, height);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top