Pointers store the address of variables or a memory location.
1.2. To Use Pointers in C, We Must Understand These Two Unary Operators (* and &)
To declare a pointer variable, we must use the unary operator * (asterisk) before its name.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<stdio.h>intmain()
{
int x =10;
int*prt;
/* The & operator before x is used to get
* the address of x and then this address
* is assigned to ptr. */ ptr =&x;
return(0);
}
To access the address of a variable in a pointer, we use the unary operator & (ampersand) that returns the address of the variable it is pointing to. For example, &x gives us the address of the variable x.
1
2
3
4
5
6
7
8
9
10
#include<stdio.h>intmain()
{
int x;
/* Prints the address of x */printf("%p", &x);
return(0);
}
To access the value stored at the address, we use the unary operator * (asterisk), which returns the value of the variable located at the address specified by its operand.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<stdio.h>intmain()
{
int x =10;
int*ptr =&x;
printf("Value of x = %d\n", *ptr);
printf("Address of x = %p\n", ptr);
*ptr =20;
printf("After doing *ptr = 20, now *ptr is %d\n", *ptr);
printf("After doing *ptr = 20, now x is %d\n", x);
return(0);
}
Please refer to the picture below to gain a better understanding of what this code is doing.
1.3. Pointer Expressions and Pointer Arithmetic
A limited set of arithmetic operations can be performed on pointers. A pointer may be:
incremented (++)
decremented (–)
An integer may be added to a pointer (+ or +=)
An integer may be subtracted from a pointer (- or -=)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<stdio.h>intmain()
{
int v[3] = {10, 20, 30};
int*ptr;
ptr = v;
for (int i =0; i <3; i++) {
printf("Value of *ptr = %d\n", *ptr);
printf("Value of ptr = %p\n", ptr);
ptr++; /* Increments pointer ptr by 1 (the size of an integer = 4) */ }
}
1.4. Array Name as Pointers
An array name acts like a pointer constant. The value of this pointer constant is the address of the first element. For example, if we have an array named v, then v and &v[0] can be used interchangeably.
1
2
3
4
5
6
7
8
9
10
#include<stdio.h>intmain()
{
int v[3] = {10, 20, 30};
int*ptr;
ptr = v; /* The same as ptr = &v[0]; */printf("The elements of the array are: %d - %d - %d\n", ptr[0], ptr[1], ptr[2]);
}
1.5. Pointers and Multidimensional Arrays
A pointer notation for the two-dimensional numeric arrays, consider the following declaration
1
int nums[2][3] = { {16, 18, 20}, {25, 26, 27} };
In general, nums[i][j] is equivalent to *(*(nums+i)+j)