The C Language

the sizeof operator

How many bytes does an int take on this machine? How big is this struct, padding and all? Rather than guessing or hard-coding numbers, C gives you a built-in way to ask: the sizeof operator. You apply it to a type or a value, and it gives back the number of bytes that type or value occupies in memory.

Write sizeof(int) to get the size of the int type, or sizeof(x) to get the size of the variable x; the result is a value of type size_t (an unsigned integer type meant for sizes). The crucial and often-missed fact is that sizeof is a COMPILE-TIME operator, not a runtime function call — the compiler computes the answer while building the program, so there is no cost when it runs, and the operand is generally not even evaluated. Because the answer is known at compile time, the standard idiom for the number of elements in an array is sizeof(arr) / sizeof(arr[0]): the whole array's bytes divided by one element's bytes.

Why this matters and the sharp caveat: sizeof is how you write portable, correct code that does not assume a type's size — you size a malloc with sizeof, and you compute array lengths with it. The trap is that the element-count trick works ONLY on a real array, not on a pointer. Once an array is passed to a function it decays to a pointer, so inside that function sizeof gives the size of the pointer (typically 8 bytes on a 64-bit machine), not the array — the length did not survive the decay, and you must pass it separately.

int arr[10]; size_t n = sizeof(arr) / sizeof(arr[0]); /* n == 10 elements */ int *p = arr; /* sizeof(p) is the pointer size (e.g. 8), NOT the array's 40 */ int *block = malloc(50 * sizeof(int)); /* size the allocation */

The element-count trick works on the real array arr but not on the pointer p, because a pointer has lost the array's length.

sizeof is a compile-time operator, not a runtime function; its operand is generally not evaluated. sizeof(array) gives the whole array's bytes, but sizeof on a pointer (including an array parameter that decayed) gives only the pointer's size — the array length does not survive decay.

Also called
sizeofsize-of operator取大小運算子