C basic data types allow access to a fixed amount of memory through variables. To work with memory more flexibly, pointers are used. A pointer stores the address of a memory location instead of a direct value. Care must be taken while working with addresses, as accessing invalid memory locations can lead to undefined behavior.
#include <stdio.h>
int main()
{
int x = 5;
int *ptr;
ptr = &x;
printf("&x = %p\n", &x);
printf("ptr = %p\n", ptr);
printf("&ptr = %p\n", &ptr);
return 0;
}
Output:
&x = 0x7ffc...
ptr = 0x7ffc...
&ptr = 0x7ffc...
ptr is a pointer to an integer, meaning it is intended to store the address of an int variable.
A pointer should 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 safely.
The address of a variable is obtained using the & operator (address-of operator).
ptr = &x stores the address of x in ptr, making ptr point to x.
Printing &x gives the address of x. Printing ptr gives the same address, since it stores that value.
The pointer variable itself also occupies memory, so &ptr gives the address of the pointer.
printf() uses %p to print memory addresses.