const char *array[] = {"ax","bo","cf"};
尝试了
printf("size of array = %lu\n", sizeof(const char*));
result != 3
也
printf("size of array = %lu\n", sizeof(array));
result != **DESIRED ANSWER** = 4
注意......我在这里已经阅读了相关的问题,但没有一个与我的问题有关......
答案 0 :(得分:6)
获取const char pointer
printf("%zu\n", sizeof(const char *));
获取数组的大小array[]
const char *array[] = {"ax","bo","cf"};
printf("%zu\n", sizeof array);
获取数组array[]
const char *array[] = {"ax","bo","cf"};
printf("%zu\n", sizeof array / sizeof array[0]); // Size of array / size of array element
// expect 3
答案 1 :(得分:1)
你需要首先找出const char *
的大小,然后你需要将此除以你的数组的大小:
#include <stdio.h>
#include<string.h>
int main()
{
const char *array[] = {"ax","bo","cf"};
printf("%d",sizeof(array)/sizeof(const char*));
return 0;
}
答案 2 :(得分:1)
anyType array[3] = {};
sizeof(array[0]) //will return the size of one element of any array
sizeof(array) //will return the storage requirement of the entire array
(sizeof(array)/sizeof(array[0])) //will return the number of elements in the array
但请记住,sizeof()在编译时解析,因此只有在拥有实际的数组变量而不是指向元素的指针时它才有效。这意味着您无法将数组传递给函数,然后获取传递参数的sizeof(),除非您将参数声明为固定大小的数组。