Pointers
Lesson 27Author : Afrixi
Last Updated : January, 2023
In C, a pointer is a variable that stores the memory address of another variable. Pointers are used to manipulate and access memory directly in C. Here is an example of how pointers work:
#include <stdio.h>
int main() {
int var = 10; // define an integer variable called var with value 10
int *ptr = &var; // define a pointer variable called ptr that points to the address of var
printf("var value: %d\n", var); // print the value of var
printf("var address: %p\n", &var);// print the memory address of var
printf("ptr value: %p\n", ptr); // print the value of ptr
printf("ptr points to: %d\n", *ptr);// print the value stored at the memory address pointed to by ptr
return 0;
}
In this example, we define an integer variable called var
and initialize it with the value 10. Then, we define a pointer variable called ptr
using the *
symbol to indicate that it is a pointer to an integer. We set the value of ptr
to the memory address of var
using the &
operator.
We then use printf
statements to print out the value of var
, the memory address of var
, the value of ptr
, and the value stored at the memory address pointed to by ptr
. The last printf
statement uses the *
symbol to dereference the pointer and access the value stored at the memory address it points to.
Output:
var value: 10
var address: 0x7fff5fbff5d4
ptr value: 0x7fff5fbff5d4
ptr points to: 10
As you can see, the value of var
is 10, its memory address is 0x7fff5fbff5d4
, and the value of ptr
is the same memory address. We then use the *
symbol to dereference the pointer and access the value stored at the memory address it points to, which is 10.