This example extends pointer usage by showing how to access the value stored at the address held by a pointer. Pointers store addresses, and dereferencing is used to read or modify the value at that address.
#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);
return 0;
}
Output:
x = 5
Value at address pointed by ptr = 5
ptr is a pointer to an integer and stores the address of x.
A pointer should always hold a valid memory address. Instead of assigning a random 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.
To access the value stored at that address, the dereferencing operator * is used.
*ptr reads the value present at the memory location pointed to by ptr, which is the value of x.
printf() uses %d to print integer values.