static char* theFruit[] = { "lemon", "orange", "apple", "banana" };
我通过观察这个数组知道它的大小是4。如何在C中以编程方式找到此数组的大小?我不想要字节大小。
atmip9wb1#
sizeof(theFruit) / sizeof(theFruit[0])
注意,sizeof(theFruit[0]) == sizeof(char *)是一个常数。
sizeof(theFruit[0]) == sizeof(char *)
cygmwpex2#
使用const char* 代替,因为它们将存储在只读位置。而要得到数组unsigned size = sizeof(theFruit)/sizeof(*theFruit);的大小,*theFruit和theFruit[0]都是相同的。
unsigned size = sizeof(theFruit)/sizeof(*theFruit);
3qpi33ja3#
有这个宏总是一件好事。
#define SIZEOF(arr) (sizeof(arr) / sizeof(*arr))
3条答案
按热度按时间atmip9wb1#
注意,
sizeof(theFruit[0]) == sizeof(char *)
是一个常数。cygmwpex2#
使用const char* 代替,因为它们将存储在只读位置。而要得到数组
unsigned size = sizeof(theFruit)/sizeof(*theFruit);
的大小,*theFruit和theFruit[0]都是相同的。3qpi33ja3#
有这个宏总是一件好事。