@voltagex
It's a standard trick to get the number of elements in an array:
sizeof(x) returns the allocated memory for the whole of the array. If your array has 10 elements and an element is a 32-bit int, then it returns 10 (elements) times 4 (bytes in a 32-bit int) = 40
sizeof(x[0]) dereferences the array to get the size of the first element. So in the same example, you get back 4.
Dividing 40 by 4 yields 10, the number of elements
It's a standard trick to get the number of elements in an array:
sizeof(x) returns the allocated memory for the whole of the array. If your array has 10 elements and an element is a 32-bit int, then it returns 10 (elements) times 4 (bytes in a 32-bit int) = 40
sizeof(x[0]) dereferences the array to get the size of the first element. So in the same example, you get back 4.
Dividing 40 by 4 yields 10, the number of elements
- replies
- 1
- announces
- 0
- likes
- 0
@voltagex
This only works for arrays allocated on the stack, not for a pointer to a 40-byte region, as for that sizeof(x) returns the size of the pointer, which is a constant that has nothing to do with the size of your array.
I'm sure you didn't need to know any of that, but now you do 😂
This only works for arrays allocated on the stack, not for a pointer to a 40-byte region, as for that sizeof(x) returns the size of the pointer, which is a constant that has nothing to do with the size of your array.
I'm sure you didn't need to know any of that, but now you do 😂