Pointers in C
A pointer in C can be declared and initialized in two steps:
int a = 10; int *p; p = &a;
The declaration says: "this variable holds a memory address. At that memory address is a value of type integer."
The memory table might look like this:
Mem Addr | Value |
40452 | 10 |
40453 | 40452 |
The initialization and declaration can be done in one step:
int *p = &a;
To get the memory address of a variable, we use &
. To get the value at a memory address, we use *
.
In C, arguments are passed by value. So, to modify the value of a variable, we need to pass a pointer to that variable:
void add_n(int *p, int n) { *p = *p + n; } int main() { int num = 1, n = 1; add_n(&num, n); return 0; }
When we call add_n()
, we are passing a memory address to the function. The function expects a memory address at which an integer resides. In add_n()
, we change the value that is stored at the memory address.
1. What if we want to change what a pointer points to?
Then, we should pass a pointer to the pointer.
void modify_ptr(int **p) { *p = new_memory_address; } int a = 10; int *p = &a; modify_ptr(&p);
In the above, int **p
is a pointer to a pointer to an int. That is, it is the memory address of the pointer p
. Then:
p
is a variable that holds a memory address, at which is stored a memory address*p
is the value pointed at byp
. This value is itself a memory address that points to an integer.**p
is the integer.
The memory table looks like this:
Memory Addr | Value | Value Accessed By |
40452 | 10 | **p = 10 |
40453 | 40452 | *p = 40452 |
40454 | 40453 | p = 40453 |