sizeof abuse : get the size of a const table
Posted
by shodanex
on Stack Overflow
See other posts from Stack Overflow
or by shodanex
Published on 2010-03-26T14:41:08Z
Indexed on
2010/03/26
14:43 UTC
Read the original article
Hit count: 331
When declaring a const table, it is possible to get the size of the table using sizeof. However, once you stop using the symbol name, it does not work anymore. is there a way to have the following program output the correct size for table A, instead of 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;
}
Output is :
size of table A : 0
size of table B : 2
© Stack Overflow or respective owner