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.
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.
sizeof(theFruit) / sizeof(theFruit[0])
Note that sizeof(theFruit[0]) == sizeof(char *)
, a constant.
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 char*
s pointing to strings. –
Vulnerable It's always a good thing to have this macro around.
#define SIZEOF(arr) (sizeof(arr) / sizeof(*arr))
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.
© 2022 - 2024 — McMap. All rights reserved.