Array of pointers
Array of Pointers An array of pointers is a collection of pointers stored in contiguous memory locations. Each element in the array points to a single me...
Array of Pointers An array of pointers is a collection of pointers stored in contiguous memory locations. Each element in the array points to a single me...
An array of pointers is a collection of pointers stored in contiguous memory locations. Each element in the array points to a single memory location, and the array itself stores the addresses of these memory locations.
Think of it as:
A table of addresses, where each cell points to a specific location in memory.
A single variable that stores the address of another variable.
A collection of pointers where each pointer points to a different element in the array.
Benefits of using arrays of pointers:
Sharing memory: You can directly access elements in multiple arrays using a single pointer.
Dynamic memory allocation: You can allocate memory dynamically during runtime, making it suitable for large datasets.
Efficient data access: Accessing elements in an array is faster than accessing elements in a linked list, especially for large datasets.
Examples:
c
char **names[3];
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";
// Accessing elements
printf("%s", names[1]); // Output: Bob
c
int *data;
data = malloc(10 * sizeof(int)); // Allocate 10 ints of memory
// Use data[i] for accessing elements
free(data); // Release allocated memory
Further points:
An array of pointers can point to any type of memory, not just other arrays.
Each element in an array points to the same memory location as the next element.
You can use array of pointers to implement linked lists and other data structures.
Remember:
Use the right type of pointer based on the pointed data type.
Use array indexing for accessing elements efficiently.
Free allocated memory to avoid memory leaks