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.

0

3 Answers 3

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

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

Sign up to request clarification or add additional context in comments.

4 Comments

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.
@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.
I think what I am confused about is that the entries are variable size because they are strings.
@eat_a_lemon: the entries aren't strings; they're char*s pointing to strings.
1

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

#define SIZEOF(arr) (sizeof(arr) / sizeof(*arr))

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.