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.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
eat_a_lemon
  • 3,158
  • 11
  • 34
  • 50

3 Answers3

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

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

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • 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. – Israel Unterman Apr 23 '12 at 15:23
  • 1
    @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. – Fred Foo Apr 23 '12 at 15:23
  • I think what I am confused about is that the entries are variable size because they are strings. – eat_a_lemon Apr 23 '12 at 15:30
  • 9
    @eat_a_lemon: the entries aren't strings; they're `char*`s *pointing to* strings. – Fred Foo Apr 23 '12 at 15:31
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.

0

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

#define SIZEOF(arr) (sizeof(arr) / sizeof(*arr))
Dav
  • 17
  • 4