sizeof abuse:获取const表的大小

sho*_*nex 1 c sizeof

声明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表的大小,给定一个指向表而不是符号名的指针?

Goz*_*Goz 5

你要求指针的大小.这总是指针大小(即32位机器上通常为4个字节,64位机器上为8个字节).在第二次尝试中,您要求的是数组的大小,因此您可以得到您期望的结果.

  • C根本不这样做.它的指针并不神奇地知道它们指向的数组的大小.如果他们这样做,那将是奇怪的.想象一下指向数组中间条目的指针:返回的sizeof()`是什么?现在,它是指针的大小或指向的元素的大小(取决于解除引用级别).那就建立了,为什么指向阵列的开始更特别?(答案:不是.) (2认同)