A pointer is a variable that stores the memory address of another variable. The & operator is used to get the address, and * is used to dereference the address.
int a = 10;
int *p = &a;
printf("%d", *p); // Outputs: 10
Pointers can point to any data type: int, char, float, etc. They allow indirect manipulation of variable values.
float pi = 3.14;
float *ptr = π
*ptr = 3.14159;
You can increment/decrement pointers to move across memory addresses. This is mainly useful in arrays.
int arr[] = {1, 2, 3};
int *p = arr;
printf("%d", *(p + 1)); // Outputs: 2
Array names work like pointers. You can access array elements using pointer arithmetic.
int arr[3] = {10, 20, 30};
int *ptr = arr;
for(int i = 0; i < 3; i++) {
printf("%d ", *(ptr + i));
}
Pointers allow functions to modify variables passed as arguments (pass by reference).
void update(int *x) {
*x = 100;
}
int main() {
int a = 10;
update(&a);
printf("%d", a); // Outputs: 100
}
Double pointers store the address of another pointer. Used in dynamic memory and function references.
int x = 5;
int *p = &x;
int **pp = &p;
printf("%d", **pp);
Memory can be allocated at runtime using malloc, calloc, and resized with realloc. Always free the memory.
int *p = (int*) malloc(sizeof(int));
*p = 25;
free(p);
Character arrays and string literals are manipulated using pointers.
char *str = "Hello";
printf("%c", *(str+1)); // Outputs: 'e'
Use -> to access members via structure pointers.
struct Student { int id; } s = {1};
struct Student *sp = &s;
printf("%d", sp->id);
void greet() { printf("Hello"); }
void (*fp)() = greet;
fp();
Pointers are essential for dynamic data structures like:
free()free()