DEV Community

AZIZ NAJLAOUI
AZIZ NAJLAOUI

Posted on

1 1 1 1 1

pointer of a pointer in c

Did you know that variables have addresses in memory? Imagine a variable as a home—it contains a value and an address. A pointer is a variable that stores the address of another variable.

To initialize a pointer, we need to specify the type of variable it will point to:

int *p;

Enter fullscreen mode Exit fullscreen mode

Here, p is declared as a pointer to an integer.

Assigning an Address to a Pointer

We use the address-of operator (&) to assign the address of a variable to a pointer:

int x = 5;
p = &x;

Enter fullscreen mode Exit fullscreen mode

If we print p, it will output a random-looking number—this is the memory address of x. However, if we print p, we get the value stored at that address (which is 5). This operation is called **dereferencing.*

printf("I'm p, the address of x: %p\n", p); // Address of x
printf("I'm *p, the value of x: %d\n", *p); // 5

Enter fullscreen mode Exit fullscreen mode

Note: When printing memory addresses, it's better to use %p instead of %d.

Modifying a Variable Through a Pointer

*p = 20;
printf("%d", x); // 20

Enter fullscreen mode Exit fullscreen mode

This means that changing *p also changes x.

Pointer to a Pointer (Double Pointer)

Even a pointer has its own memory address, and we can store that address in another pointer! To initialize a pointer that holds the address of another pointer, we write:

int **q;
q = &p;

Enter fullscreen mode Exit fullscreen mode

The first * indicates that q is a pointer.
The second * means that q stores the address of another pointer.

Accessing Values Using a Double Pointer

Since q holds the address of p,

  • *q is the value inside p, which is the address of x.

  • **q is the value of x.
    More simply:

  • q → Address of p.

  • *q → Value inside p (which is &x).

  • **q → Value inside x (which is 5).
    Final Code

#include <stdio.h>

int main() {
    int *p;
    int x = 5;

    p = &x;

    int **q;
    q = &p;

    printf("I'm q, the address of p: %p\n", q);
    printf("I'm the address of p: %p\n", &p);
    printf("I'm the value of p (the address of x): %p\n", *q);
    printf("I'm the address of x: %p\n", &x);
    printf("I'm the value of x: %d\n", x);
    printf("I'm the value of the variable with address p (so I'm x): %d\n", **q);

    return 0;
}

Enter fullscreen mode Exit fullscreen mode

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)