C sizeof Operator
Discussions center on the behavior, pitfalls, and best practices of the sizeof operator in C, especially differences between arrays and pointers, compile-time evaluation, and calculating array lengths.
Activity Over Time
Top Contributors
Keywords
Sample Comments
How does this not break sizeof ?
That mindset doesn't cover sizeof(a) properly.
Simple rule: Don't use sizeof on pointers. And don't typedef arrays to make them look like simple types.
Downvoters, care to elaborate what you think is wrong with the above? Literally even fortran can do better than size_t len_a = sizeof(a)/sizeof(a[0]); or my_pseudo_foo_array = (foo*) malloc(len * sizeof(foo));
You must pass a size_t somewhere, surely? Otherwise you have no idea how long the array is - this is about doing it properly rather than relying on yourself at 9AM to get it right everytime.
The sizeof operator begs to differ.
Does that even work in C when sizeof x[i] > 1?
Working within the "contrived example" framework, it would have made a little more sense if buffer were a pointer rather an array, in which case you wouldn't be able to use "sizeof".
They don't, sizeof is a compile-time constant. On a pointer, sizeof() just reports the size of the pointer itself (i.e. 4 or 8 bytes on most modern platforms), not the size of the data to which it points (and sizeof(*pointer) reports the size of the type to which pointer points, it doesn't know anything about how many values of that type are stored). For an array, the length is known statically (i.e. it's in the type), and so the computation can be done at compile time.
C arrays “know” their size. (String literals do too.)