Pointers
Pointers
Syntax of C Pointers
The syntax of pointers is similar to the variable declaration in C, but
we use the ( * ) dereferencing operator in the pointer declaration.
datatype * ptr;
1. Pointer Declaration
2. Pointer Initialization
3. Pointer Dereferencing
1. Pointer Declaration
In pointer declaration, we only declare the pointer but do not initialize it. To
declare a pointer, we use the ( * ) dereference operator before its name.
Example
int *ptr;
The pointer declared here will point to some random memory address as it is
not initialized. Such pointers are called wild pointers.
2. Pointer Initialization
Pointer initialization is the process where we assign some initial value to the
pointer variable. We generally use the ( & ) addressof operator to get the
memory address of a variable and then store it in the pointer variable.
Example
int var = 10;
int * ptr;
ptr = &var;
We can also declare and initialize the pointer in a single step. This method is
called pointer definition as the pointer is declared and initialized at the same
time.
Example
int *ptr = &var;
3. Pointer Dereferencing
Dereferencing a pointer is the process of accessing the value stored in the
memory address specified in the pointer. We use the same ( * ) dereferencing
operator that we used in the pointer declaration.
C Pointer Example
// C program to illustrate Pointers
#include <stdio.h>
void geeks()
{
int var = 10;
// Driver program
int main()
{
geeks();
return 0;
}
Output
Value at ptr = 0x7fff1038675c
Value at var = 10
Value at *ptr = 10
Result:
25
50
75
100
Instead of printing the value of each array element,
let's print the memory address of each array element:
Example
int myNumbers[4]={25, 50, 75, 100};
int i;
Result:
0x7ffe70f9d8f0
0x7ffe70f9d8f4
0x7ffe70f9d8f8
0x7ffe70f9d8fc
The memory address of the first element is the same as the name of the
array:
Example
int myNumbers[4]={25, 50, 75, 100};
//GetthememoryaddressofthemyNumbersarray
printf("%p\n",myNumbers);
//Getthememoryaddressofthefirstarrayelement
printf("%p\n", &myNumbers[0]);
Result:
0x7ffe70f9d8f0
0x7ffe70f9d8f0
Since myNumbers is a pointer to the first element in myNumbers, you can
use the * operator to access it:
Example
int myNumbers[4]={25, 50, 75, 100};
// Get the value of the first element in myNumbers
printf("%d", *myNumbers);
To access the rest of the elements in myNumbers, you can increment the
pointer/array (+1, +2, etc):
Example
int myNumbers[4]={25, 50, 75, 100};
// and so on..
Result:
50
75
50
75
100
Example
int myNumbers[4]={25, 50, 75, 100};
13
17