C - Pointer Concepts and Addressing Mechanism in C
Pointer – Definition
A pointer is a variable that stores the memory address of another variable instead of storing a direct value.
Example:
int a = 10;
int *p = &a;
Here:
-
astores value10 -
pstores the address ofa
Addressing Mechanism in C
The addressing mechanism refers to how C programs access memory locations using addresses and pointers.
C supports direct addressing and indirect addressing.
Direct Addressing
-
Variable is accessed directly by its name
-
Uses the actual memory location internally
Example:
int a = 5;
printf("%d", a);
Indirect Addressing
-
Variable is accessed through its address using pointers
-
Uses dereferencing operator (
*)
Example:
int a = 5;
int *p = &a;
printf("%d", *p);
Here:
-
&a→ address ofa -
*p→ value stored at that address
Pointer Operators
1. Address-of Operator (&)
-
Returns the address of a variable
Example:
int a = 10;
printf("%p", &a);
2. Dereference Operator (*)
-
Accesses the value stored at an address
Example:
int *p;
*p = 20;
Types of Pointers
1. Integer Pointer
int *p;
2. Pointer to Pointer
-
Stores address of another pointer
Example:
int **pp;
3. Null Pointer
-
Points to nothing
-
Prevents accidental access
Example:
int *p = NULL;
4. Void Pointer
-
Can point to any data type
-
Must be type-cast before dereferencing
Example:
void *p;
5. Dangling Pointer
-
Points to memory that has been freed
Example:
free(p); // p becomes dangling
Pointer Arithmetic
Pointer arithmetic depends on the data type size.
Example:
int *p;
p = p + 1; // moves by sizeof(int)
Relationship Between Arrays and Pointers
-
Array name stores base address
-
Pointer can access array elements
Example:
int a[3] = {10, 20, 30};
int *p = a;
Access:
*(p + 1) = 20;
Advantages of Pointers
-
Efficient memory access
-
Used in dynamic memory allocation
-
Essential for data structures
-
Enables function call by reference
Disadvantages of Pointers
-
Complex to understand
-
Can cause memory leaks
-
Risk of dangling and wild pointers