Pointer in C
In C, a pointer is a variable that stores the memory address of another variable. It provides a way to indirectly access and manipulate data stored in memory.
Declaration
A pointer is declared using the *
operator followed by the data type of the variable it will point to:
data_type *pointer_name;
For example, to declare a pointer to an integer:
int *ptr;
Initialization
A pointer can be initialized to point to a variable using the &
operator:
int x = 10;
int *ptr = &x;
Now, ptr
stores the memory address of the variable x
.
Dereferencing Pointers
To access the value stored at the memory location pointed to by a pointer, you use the *
operator:
int y = *ptr; // y will be 10
Pointers to Pointers in C
A pointer to a pointer is a variable that stores the memory address of another pointer. It provides a level of indirection, allowing you to modify pointers indirectly.
Declaration:
data_type **pointer_to_pointer;
For example, to declare a pointer to a pointer to an integer:
int **ptr_to_ptr;
Initialization:
A pointer to a pointer can be initialized to point to another pointer:
int x = 10;
int *ptr = &x;
int **ptr_to_ptr = &ptr;
Example:
#include <stdio.h>
int main() {
int x = 10;
int *ptr = &x;
int **ptr_to_ptr = &ptr;
printf("Value of x: %dn", x);
printf("Value of ptr: %pn", ptr);
printf("Value of ptr_to_ptr: %pn", ptr_to_ptr);
// Modify x through ptr_to_ptr
**ptr_to_ptr = 20;
printf("Modified value of x: %dn", x);
return 0;
}
Types of Pointers
- Single Pointers: These pointers point to a single variable.
- Array Pointers: These pointers point to the first element of an array.
- Function Pointers: These pointers point to a function.
- Void Pointers: These pointers can point to any data type.
Pointer Arithmetic
You can perform arithmetic operations on pointers, but the operations are specific to the data type they point to. For example, if ptr
is a pointer to an integer, ptr + 1
will point to the next integer in memory.
Example:
#include <stdio.h>
int main() {
int x = 10;
int *ptr = &x;
printf("Value of x: %dn", x);
printf("Address of x: %pn", &x);
printf("Value of ptr: %pn", ptr);
printf("Value pointed
to by ptr: %dn", *ptr);
*ptr = 20;
printf("Modified value of x: %dn", x);
return 0;
}
Key Points:
- Pointers provide indirect access to memory.
- Use the
*
operator to dereference a pointer and access the value it points to. - Use the
&
operator to get the address of a variable. - Be careful when using pointers to avoid memory leaks and segmentation faults.
- Understand the different types of pointers and their uses.