Kevin Cheng
Kevin Cheng

Reputation: 39

Dynamically allocated 2 dimensional arrays

Does anyone know what the third line "Free(array)" does? array here is just the address of the first element of array(in other words, a pointer to the first element in the array of int * right)? Why do we need the third line to free the "columns" of the 2D array? I basically memorized/understand that a is a pointer to means a holds the address of ____. Is this phrase correct?

For example: int **a; int * b; int c; b = &c = 4; a = &b; This is correct right? Thankyou!!!

Also, in general, double pointers are basically dynamically allocated arrays right?

"Finally, when it comes time to free one of these dynamically allocated multidimensional ``arrays,'' we must remember to free each of the chunks of memory that we've allocated. (Just freeing the top-level pointer, array, wouldn't cut it; if we did, all the second-level pointers would be lost but not freed, and would waste memory.) Here's what the code might look like:" http://www.eskimo.com/~scs/cclass/int/sx9b.html

for(i = 0; i < nrows; i++)
    free(array[i]);
free(array);

Upvotes: 0

Views: 113

Answers (2)

Adam
Adam

Reputation: 75

Calls to malloc allocate memory on the heap, equal to the number of bytes specified by its argument, and returns the address of this block of memory. Your '2D array' is really a 1D array of int addresses, each pointing to a chunk of memory allocated by malloc. You need to free each of these chunks when you are done, making it available for others to use. But your 1D array is really just another malloc'd chunk of memory to hold these malloc'd addresses, and that needs to be freed also.

Also, when you use printf("%s", array) where array is an char *, the compiler sees the array as the address of array[0] but prints it right? I'm just curious if I'm understanding it right.

Yes, %s tells printf to go to whatever address you give it (an address of a char, aka a char*, let's say), and start reading and displaying whatever is in memory at that address, one character at a time until it finds a 'NULL character'. So in the case of a string, that is the expected behavior, since a string is just an array of chars, followed by the '\0' char.

Upvotes: 0

NPE
NPE

Reputation: 500883

Why do we need the third line to free the "columns" of the 2D array?

The number of deallocations should match up with the number of allocations.

If you look at the code at the start of the document:

int **array;
array = malloc(nrows * sizeof(int *));
for(i = 0; i < nrows; i++) {
    array[i] = malloc(ncolumns * sizeof(int));
}

you'll see that there is one malloc() for the array itself and one malloc() for each row.

The code that frees this is basically the same in reverse.

Also, in general, double pointers are basically dynamically allocated arrays right?

Not necessarily. Dynamically allocated arrays is one use for double pointers, but it's far from the only use.

Upvotes: 2

Related Questions