Table of contents
This piece serves as an intro to pointers in the C language. I have tried to present this intricate topic in a simple manner.
Enjoy ๐
\* If you have any queries, feel free to put those in the comments*
Variables: A Refresher
Every variable in C has a name and a value. Consider
int a = 9;
When the above statement executes, a chunk of memory (4 bytes in this case) is allocated to store the value 9. The compiler also sets up a symbol table, in which it adds the symbol a
with its corresponding memory address (it refers to the location where the 4 bytes were set aside). Thus, every variable is also associated with an address.
N.B. The value of a variable always appears on the right side of the assignment operator. Extending the above line of code,
int b = a;
Here, a
refers to the value stored in the memory space allotted to a
. So now, b
is also 9.
Pointers
A pointer is a variable that stores the memory address of another variable or array.
type *name;
(pointer declaration)
type
refers to the data type of the variable that the pointer is "pointing to".
#include<stdio.h>
int main()
{
int num = 7, *ptr;
ptr = #
printf("Address: %p \n", ptr);
printf("Value: %d \n", *ptr);
return 0;
}
Once declared,
*ptr
refers to the value in the memory address assigned to it.The address of a variable cannot be changed.
Arrays
Imagine any int
array a[]
The following bullets elucidates its connection to pointers:
The name,
a
, of the array is known as the base address, it refers to the address of the first element,a[0]
int *pa = a;
assigns the address ofa[0]
to the pointer. To mutatepa
, usepa += i
, which re-assignspa
with the address ofa[i]
.Syntax sugar:
a[i]
is equivalent to*(a + i)
๐ Misconception
Some think that the array name is a pointer, but an assignment like a = pa
is invalid. This is because pa
is a variable, whereas a
is a constant. Once a[]
has been declared, the memory address allocated to a[0]
is immutable. Hence, the array name can be thought of as a constant pointer.
๐ Pointer Arithmetic
We can add integers to a pointer to get a new pointer that stores the address of a different location than the original pointer. Let
pa1
andpa2
be twoint
pointers. Saypa1 = &a[1]
, thenpa2 = pa + 3
points toa[4]
.It is possible to subtract two pointers, provided they are pointing to the same array. E.g.,
printf("%ld", pa2 - pa1);
gives 3, which is the number of elements betweenpa1
andpa2
.We can also use relational operators with pointers. If
pa1 < pa2
, it meanspa1
is pointing to an element nearer to the beginning (index 0) thanpa2
.
Grateful for your attention ๐
See ya ๐ฉต