[C Language] Pointers (void* & Double Pointers)
daily
[C Language] Pointers (void* & Double Pointers)
π Date: 2025.08.19
1. void* Pointer
c#include <stdio.h> int main() { int a = 100; double b = 3.14; void *vp; vp = &a; printf("a = %d\n", *(int*)vp); vp = &b; printf("b = %.2f\n", *(double*)vp); }
π void* can be thought of as a βcontainer for addresses.β
π To access the actual value, you must cast it back to the proper type.
2. Double Pointer
A double pointer: a pointer to another pointer
Commonly used in: dynamic allocation of 2D arrays
c#include <stdio.h> #include <stdlib.h> int main() { int rows = 3, cols = 4; int **matrix = malloc(rows * sizeof(int*)); // array of row pointers for (int i = 0; i < rows; i++) { matrix[i] = malloc(cols * sizeof(int)); // allocate each row } // assign values for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { matrix[i][j] = i * cols + j; printf("matrix[%d][%d] = %d (address: %p)\n", i, j, matrix[i][j], (void*)&matrix[i][j]); } } // free memory for (int i = 0; i < rows; i++) free(matrix[i]); free(matrix); }
β Summary
matrix itself is an array of int*
Each matrix[i] points to another array of ints
3. Pointer and Address/Value Relationship
cint a = 10; int *p = &a; // p stores the address of a *p; // value at that address (10)
π Meaning of *:
next to type β pointer declaration
in front of variable β dereference (get value from address)
π Key Takeaways
void* = generic pointer (needs casting)
Double pointer = essential for dynamic 2D arrays
'*' = declaration vs dereference, depending on context