Welcome back to CodeYourCraft! Today, we're diving deep into the world of C Pointer to Pointer 🎯, a topic that's essential for advanced C programming. Let's start with the basics and gradually build up to more complex concepts.
In C programming, a pointer is a variable that stores the memory address of another variable. A pointer to pointer (also known as a double pointer) is a variable that stores the memory address of a pointer.
Let's illustrate this with an example:
int num = 10;
int *ptr = # // Here, ptr is a pointer that stores the memory address of num.
int **d_ptr = &ptr; // Here, d_ptr is a pointer to pointer that stores the memory address of ptr.In this example, d_ptr is a pointer to a pointer that points to the integer variable num.
Pointer to pointers are useful in situations where we need to dynamically allocate memory, such as creating multi-dimensional arrays, linked lists, trees, and more. They provide flexibility and efficiency in managing memory.
To declare a pointer to pointer, we use two asterisks (**). Let's create a simple example:
int **twoDArray;Here, twoDArray is a pointer to pointer that can hold the addresses of pointers, each pointing to integers.
To allocate memory for a pointer to pointer, we use the malloc() function twice: once for each level of pointers. Here's an example:
int **twoDArray;
twoDArray = (int **) malloc(rows * sizeof(int *));
for (int i = 0; i < rows; i++) {
twoDArray[i] = (int *) malloc(cols * sizeof(int));
}In this example, we first allocate memory for an array of pointers (twoDArray). Then, for each element in twoDArray, we allocate memory for an array of integers.
To access an element in a two-dimensional array represented by a pointer to pointer, we use two asterisks (**). Here's an example:
twoDArray[row_index][col_index] = 5;
int value = twoDArray[0][1]; // Accessing the element at the first row and second columnIn this example, we're setting the value at the first row and second column of twoDArray to 5, and then accessing the value at the same position.
What is a pointer to pointer in C programming?
Why do we use pointer to pointers in C programming?