Pointers in C Language:
Pointers in C
Pointers are variables that store the memory address of another variable. They provide a way to indirectly access and manipulate the value of a variable. Understanding pointers is essential for dynamic memory allocation, arrays, and various other aspects of C programming.
Pointer Declaration and Initialization
#include
int main() {
int a = 10;
int *p; // Pointer declaration
p = &a; // Pointer initialization
printf("Value of a: %d\n", a);
printf("Address of a: %p\n", (void*)&a);
printf("Value of p (address of a): %p\n", (void*)p);
printf("Value at address stored in p: %d\n", *p);
return 0;
}
Pointer Arithmetic
Pointers can be used to perform arithmetic operations. When you increment or decrement a pointer, it moves by the size of the data type it points to.
#include
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *p = arr; // Pointer to the first element of the array
printf("Address of arr[0]: %p, Value: %d\n", (void*)p, *p);
p++; // Move to the next element
printf("Address of arr[1]: %p, Value: %d\n", (void*)p, *p);
p++;
printf("Address of arr[2]: %p, Value: %d\n", (void*)p, *p);
return 0;
}
Call by Reference Using Pointers
In C, you can use pointers to achieve call by reference. This allows a function to modify the actual values of variables passed to it.
#include
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main() {
int a = 10, b = 20;
printf("Before swap: a = %d, b = %d\n", a, b);
swap(&a, &b); // Passing addresses of a and b
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}
Pointers and Arrays
Pointers can be used to access array elements. The name of an array acts as a pointer to its first element.
#include
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *p = arr; // Pointer to the first element of the array
for (int i = 0; i < 5; i++) {
printf("arr[%d] = %d\n", i, *(p + i));
}
return 0;
}
Pointer to Pointer
You can have a pointer that points to another pointer. This is known as a pointer to pointer or double pointer.
#include
int main() {
int a = 10;
int *p = &a; // Pointer to int
int **pp = &p; // Pointer to pointer to int
printf("Value of a: %d\n", a);
printf("Value of p (address of a): %p\n", (void*)p);
printf("Value of pp (address of p): %p\n", (void*)pp);
printf("Value at address stored in pp: %p\n", (void*)*pp);
printf("Value at address stored in p: %d\n", **pp);
return 0;
}