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;
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;
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
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
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;
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 insidep
, which is the address ofx
.**q
is the value ofx
.
More simply:q
→ Address ofp
.*q
→ Value inside p (which is&x
).**q
→ Value inside x (which is5
).
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;
}
Author Of article : AZIZ NAJLAOUI Read full article