static char* theFruit[] = {
"lemon",
"orange",
"apple",
"banana"
};
I know the size is 4 by looking at this array. How do I programmatically find the size of this array in C? I do not want the size in bytes.
We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);
Static arrays have their size or length determined when the array is created and/or allocated. For this reason, they may also be referred to as fixed-length arrays or fixed arrays. Array values may be specified when the array is defined, or the array size may be defined without specifying array contents.
&a + 1 => It points at the address after the end of the array. *(a+1) => Dereferencing to *(&a + 1) gives the address after the end of the last element. *(a+1)-a => Subtract the pointer to the first element to get the length of the array. Print the size.
sizeof(theFruit) / sizeof(theFruit[0])
Note that sizeof(theFruit[0]) == sizeof(char *)
, a constant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With