This example shows how a pointer can be used not only to access a value but also to modify the value stored at a memory location. By dereferencing a pointer, the data at that address can be updated.
#include <stdio.h>
int main()
{
int x = 5;
int *ptr;
ptr = &x;
printf("x = %d\n", x);
printf("Value at address pointed by ptr = %d\n", *ptr);
*ptr = 20;
printf("x = %d\n", x);
return 0;
}
Output:
x = 5
Value at address pointed by ptr = 5
x = 20
ptr is a pointer to an integer and stores the address of x.
A pointer should always hold a valid memory address. A variable is defined so that memory is allocated, and its address can be used.
The address of a variable is obtained using the & operator.ptr = &x stores the address of x in ptr.
*ptr is used to access the value stored at the address pointed to by ptr.
Using *ptr = 20 updates the value at that memory location. Since ptr points to x, the value of x is modified.
printf() uses %d to print integer values.