C查找静态数组大小

kyks70gy  于 2023-06-21  发布在  其他
关注(0)|答案(3)|浏览(80)
static char* theFruit[] = {
    "lemon",
    "orange",
    "apple",
    "banana"
};

我通过观察这个数组知道它的大小是4。如何在C中以编程方式找到此数组的大小?我不想要字节大小。

atmip9wb

atmip9wb1#

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

注意,sizeof(theFruit[0]) == sizeof(char *)是一个常数。

cygmwpex

cygmwpex2#

使用const char* 代替,因为它们将存储在只读位置。而要得到数组unsigned size = sizeof(theFruit)/sizeof(*theFruit);的大小,*theFruit和theFruit[0]都是相同的。

3qpi33ja

3qpi33ja3#

有这个宏总是一件好事。

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

相关问题