The sizeof operator with complex types
What you'll learn: How to determine the exact memory footprint of multidimensional arrays and complex pointer structures using the sizeof operator.
Thinking in bytes, not items
When you use sizeof on a simple integer, it returns 4 bytes. But as our types grow more complex, sizeof becomes a vital tool for navigating memory. The most important thing to remember is that sizeof calculates the total size of the type you provide, not the number of elements it contains.
Think of an egg carton. sizeof doesn't tell you that there are 12 eggs; it tells you the physical volume of the cardboard box itself. If you have a stack of 10 cartons, sizeof tells you the volume of the entire stack.
Deciphering the math
When dealing with multidimensional arrays, sizeof behaves predictably but can produce large numbers that surprise beginners. If you have int matrix[5][10], sizeof(matrix) will not return 50 (the total number of integers). Instead, it returns bytes (assuming a 4-byte int), totaling 200 bytes.
However, the operator is particularly powerful when you zoom in on specific parts of a complex declaration:
#include <stdio.h>
int main() {
int grid[3][4]; // A 2D array: 3 rows, 4 columns
printf("Total size: %zu\n", sizeof(grid)); // 3 * 4 * 4 = 48 bytes
printf("Row size: %zu\n", sizeof(grid[0])); // 4 * 4 = 16 bytes
printf("Item size: %zu\n", sizeof(grid[0][0])); // 4 bytes
// Complex pointer arrays
int *ptr_array[5];
printf("Pointer array: %zu\n", sizeof(ptr_array)); // 5 * 8 = 40 bytes (on 64-bit)
return 0;
}
The "Pointer Trap"
A common mistake in advanced C is confusing a complex array with a pointer. If you pass a multidimensional array to a function, it "decays" into a pointer. Inside that function, sizeof will only return the size of the pointer (usually 8 bytes), losing the information about the array's dimensions. Always apply sizeof to the original identifier in the scope where it was defined to get the true footprint of complex types.
Key takeaway
The sizeof operator evaluates the entire memory block of a complex type, allowing you to calculate dimensions by dividing the total size by the size of a single element or row.