C Pointer to Pointer Deep Dive 🔎

beginner
11 min

C Pointer to Pointer Deep Dive 🔎

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.

What is a Pointer to Pointer? 📝

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:

c
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.

Why Use Pointer to Pointer? 💡

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.

Declaring a Pointer to Pointer 📝

To declare a pointer to pointer, we use two asterisks (**). Let's create a simple example:

c
int **twoDArray;

Here, twoDArray is a pointer to pointer that can hold the addresses of pointers, each pointing to integers.

Allocating Memory for a Pointer to Pointer 💡

To allocate memory for a pointer to pointer, we use the malloc() function twice: once for each level of pointers. Here's an example:

c
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.

Accessing a Pointer to Pointer 💡

To access an element in a two-dimensional array represented by a pointer to pointer, we use two asterisks (**). Here's an example:

c
twoDArray[row_index][col_index] = 5; int value = twoDArray[0][1]; // Accessing the element at the first row and second column

In 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.

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

What is a pointer to pointer in C programming?

Quick Quiz
Question 1 of 1

Why do we use pointer to pointers in C programming?