声明const表时,可以使用sizeof获取表的大小.但是,一旦停止使用符号名称,它就不再起作用了.有没有办法让以下程序输出表A的正确大小,而不是0?
#include <stdio.h>
struct mystruct {
int a;
short b;
};
const struct mystruct tableA[] ={
{
.a = 1,
.b = 2,
},
{
.a = 2,
.b = 2,
},
{
.a = 3,
.b = 2,
},
};
const struct mystruct tableB[] ={
{
.a = 1,
.b = 2,
},
{
.a = 2,
.b = 2,
},
};
int main(int argc, char * argv[]) {
int tbl_sz;
const struct mystruct * table;
table = tableA;
tbl_sz = sizeof(table)/sizeof(struct mystruct);
printf("size of table A : %d\n", tbl_sz);
table = tableB;
tbl_sz = sizeof(tableB)/sizeof(struct mystruct);
printf("size of table B : %d\n", tbl_sz);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
size of table A : 0
size of table B : 2
Run Code Online (Sandbox Code Playgroud)
这是sizeof的预期行为.但是有没有办法让编译器知道const表的大小,给定一个指向表而不是符号名的指针?
你要求指针的大小.这总是指针大小(即32位机器上通常为4个字节,64位机器上为8个字节).在第二次尝试中,您要求的是数组的大小,因此您可以得到您期望的结果.