C find static array size
Asked Answered
C

3

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

Certainly answered 23/4, 2012 at 15:20 Comment(0)
V
50
sizeof(theFruit) / sizeof(theFruit[0])

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

Vulnerable answered 23/4, 2012 at 15:20 Comment(4)
Yes, it's exactly the way to it. That's why he's getting +1s.... :-). But only with arrays, as you have in your question. Not with pointers.Oneill
@eat_a_lemon: depends on what you call every case :) It works for static and automatic arrays, not malloc'd ones. Note that the size of the array is always a multiple of the size of the first element, so the division is guaranteed to work, and that sizeof only looks at types, so it even works for arrays with zero elements.Vulnerable
I think what I am confused about is that the entries are variable size because they are strings.Certainly
@eat_a_lemon: the entries aren't strings; they're char*s pointing to strings.Vulnerable
A
1

It's always a good thing to have this macro around.

#define SIZEOF(arr) (sizeof(arr) / sizeof(*arr))
Agglomeration answered 5/6, 2023 at 15:33 Comment(0)
F
0

Use const char* instead as they will be stored in read-only place. And to get size of array unsigned size = sizeof(theFruit)/sizeof(*theFruit); Both *theFruit and theFruit[0] are same.

Fein answered 23/9, 2021 at 9:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.