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;
}
出力は次のとおりです。
size of table A : 0
size of table B : 2
これは sizeof の意図した動作です。しかし、シンボル名の代わりにテーブルへのポインタが与えられた場合、コンパイラが const テーブルのサイズを知る方法はありますか?