A pointer is a special variable that stores the memory address of another variable. Instead of holding a direct value, a pointer contains the location in memory where the value is stored. Pointers are widely used in C programming for efficient memory management, dynamic memory allocation, passing arguments to functions, and implementing complex data structures such as linked lists, stacks, queues, and trees.
Whenever a variable is declared, the system allocates memory for it. Each memory location has a unique address. A pointer variable stores this address, allowing the program to access or modify the value stored at that location indirectly.
Syntax:
data_type *pointer_name;
Example:
int *p;
In the above declaration, p is a pointer variable that can store the address of an
integer variable.
#include
int main()
{
int a = 5;
int *p;
p = &a;
printf("Value of a = %d\n", a);
printf("Address of a = %p\n", (void*)&a);
printf("Address stored in p = %p\n", (void*)p);
printf("Value pointed to by p = %d\n", *p);
return 0;
}
Value of a = 5
Address of a = 0x7ffd3a8c4b24
Address stored in p = 0x7ffd3a8c4b24
Value pointed to by p = 5
In this example, the address-of operator (&) is used to obtain the memory address
of variable a. This address is stored in the pointer variable p. The
dereference operator (*) is then used to access the value stored at that address.
& operator returns the address of a variable.* operator is used to access the value stored at the address.