A pointer is a variable that stores the memory address of another variable.
int a = 10;
int *ptr = &a; // ptr now holds the address of variable a
Pointer Subtopics
int x = 5;
int *p = &x; // address of x
printf("%d", *p); // value at address (dereferencing)
When a variable is declared, it's stored at a specific memory location. A pointer stores this address.
For example:
int a = 5;
int *ptr = &a;
printf("Address: %p\n", ptr);
printf("Value: %d\n", *ptr);
A pointer that stores the address of another pointer.
int x = 10;
int *p = &x;
int **pp = &p;
printf("Value: %d", **pp);
Pointers can be incremented/decremented to move across memory (especially arrays).
int arr[] = {1, 2, 3};
int *p = arr;
printf("%d", *(p + 1)); // prints 2
Array names are constant pointers. You can iterate over arrays using pointers.
int arr[3] = {10, 20, 30};
int *p = arr;
for(int i = 0; i < 3; i++) {
printf("%d ", *(p + i));
}
Pointers are used to pass arguments by reference.
void modify(int *p) {
*p = 100;
}
int main() {
int x = 10;
modify(&x);
printf("%d", x); // 100
}
Using pointers and malloc/calloc to allocate memory at runtime.
int *ptr = (int*) malloc(sizeof(int));
*ptr = 50;
printf("%d", *ptr);
free(ptr);