Understanding Pointer Types in C Programming
Array Pointers
An array pointer stores the base address of an entire array. When incremented, it moves by the size of the whole array rather than a single element. This is particularly useful when working with multidimensional arrays.
int values[5] = {3,9,2,5,8};
int (*array_ptr)[5] = &values;
for(int i=0; i<5; i++) {
printf("%d\t", (*array_ptr)[i]);
}
Pointer Arrays
A pointer array contains multiple pointer variables as its elements. Each element can point to different memory locaitons.
int a = 100, b = 200, c = 300;
int *ptr_list[3] = {&a, &b, &c};
for(int i=0; i<3; i++) {
printf("%d ", *ptr_list[i]);
}
Pointer Functions
Pointer functions return memory addresses. The returned address must point to persistent memory (global, static, or heap-allocated).
int* create_value() {
static int val = 42;
return &val;
}
int main() {
int *result = create_value();
*result = 84;
printf("%d", *create_value());
}
Fnuction Pointers
Function pointers store the entry address of functions, enabling callback mechanisms and dynamic function invocation.
int add(int x, int y) { return x+y; }
int sub(int x, int y) { return x-y; }
void calculate(int a, int b, int (*op)(int,int)) {
printf("Result: %d\n", op(a,b));
}
int main() {
calculate(10, 5, add);
calculate(10, 5, sub);
}