Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C find static array size

Tags:

arrays

c

static

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.

like image 896
eat_a_lemon Avatar asked Apr 23 '12 15:04

eat_a_lemon


People also ask

How do you determine the size of an array that is static?

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]);

Is array static in size?

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.

How do you find the size of an array without using sizeof operator?

&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.


1 Answers

sizeof(theFruit) / sizeof(theFruit[0])

Note that sizeof(theFruit[0]) == sizeof(char *), a constant.

like image 178
Fred Foo Avatar answered Oct 12 '22 11:10

Fred Foo