2 ms·
On the contrary: the sizeof operator is the only way to generally get the size of an arbitrary array (with e.g. no known sentinel to mark its last element) in C
by eMSF 4y ago
On the contrary: the sizeof operator is the only way to generally get the size of an arbitrary array (with e.g. no known sentinel to mark its last element) in C. You couldn't use a function instead even if you wanted to.
Many other languages however don't have the equivalent of the sizeof operator because they don't expose an object's memory representation quite as much as C does.
- raverbashing 4y agoYou're right, but it only works for fixed-sized arrays (which are not as common). Also for a learner it is very easy to think that I can do: int * my_array; my_array = malloc(100*sizeof(int)); int array_length = sizeof(my_array);
- enriquto 4y ago> it only works for fixed-sized arrays It also works for variable length arrays. void f(int n) { float a[n]; int m = sizeof a / sizeof *a; assert(n == m); }
- kevin_thibedeau 4y agoIn this case my_array isn't an array. Misleading learners that arbitrary blocks of memory are "arrays" is the bigger travesty.