我正在尝试使用这个技巧,通过将数组大小除以类型的大小来获取数组中的项目数:sizeof(array) / sizeof(<type>)
或sizeof(array) / sizeof(array[0])
出于我不完全理解的原因,当我尝试将数组作为类型 const char**
的函数的参数时然后调用sizeof()
,它总是返回 8。
#include <stdio.h>
void write(const char** arr) {
printf("%ld", sizeof(arr));
}
int main() {
const char* word[] = {
"asdf",
"qwer",
"hjkl"
};
write(word);
return 0;
}
>> 8
所以sizeof(array) / sizeof(const char*)
结果总是 1。
发生什么事了?
最佳答案
这真的是你的printf()
吗?如果是这样,那就完全错误了,你没有格式字符串:
int main(void) {
const char* word[] = {
"asdf",
"qwer",
"hjkl"
};
printf("%zu\n", sizeof(word));
}
输出:
12
关于c - sizeof(<字符串数组>) 始终返回 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49593768/