Pointer Arrays Flashcards
Defining Pointer Arrays
T* ptr_array [<length>];</length>
ptr_to_array has type T*[<length>] which is an
array type whose elements are pointers to type T.</length>
its type decays to TRea**, that is a pointer to a pointer of type T.
Accessing/Modifying Elements through an Array of Pointers
like 2D array
Deallocating a Pointer Array
we must free any memory that the array points to that
was dynamically allocated.
// Free the memory we allocated for number_lists
for( size_t i =0; i < num_ptrs ; i = i + 1) {
free ( number_lists [i]);
}
we do not have to free the array number_lists because it was automatically allocated.
dynamically allocating the pointer array itself
line 7 is now int**. This is read as “a pointer to a pointer to an integer” or “a pointer to an integer pointer”.
Arrays of Pointers to Characters (Arrays of Strings)
Pointer arrays of type char*[] can be used to store arrays of strings.
The strdup() function combines a malloc() and a strcpy().
It takes a string (char*) as an argument, dynamically allocates a new memory block large enough to hold its argument, copies its argument into the new memory, and returns a pointer to the new memory
Accessing Arrays of Strings
Replacing a string
We could copy a new string overtop of one of the existing strings, provided
that the new string is not longer than the existing string:
strncpy ( names [2] , “ Princess Bubblegum “, strlen ( names [2]));
This would copy the first 5 characters of “Princess Bubblegum” into names[2], overwriting
“Beemo”. We can’t copy more than 5 characters, because “Beemo” was dynamically allocated by
strdup(), thus there is only enough storage for 5 characters plus the null character