c中结构的大小等于1

1 c struct

出于某种原因,如果我试图获得实际尺寸,mystruct我会继续获得尺寸1.

我知道这mystruct是持有数据,因为我可以把它丢弃,一切都在mystruct.

获得1号大小的原因是什么?谢谢

// fragments of my code
struct mystruct {
    char *raw;
    int  count;
};

struct counter {
    int total; // = 30
}

static struct mystruct **proc()
{
    int i = 0;
    gchar *key,*val;
    struct mystruct **a_struct;
    struct counter c;

    a_struct = (struct mystruct **)malloc(sizeof(struct mystruct *)*c.total);
    while (table (&iter, (gpointer) &key, (gpointer) &val)) {

        a_struct[i] = (struct mystruct *)malloc(sizeof(struct mystruct));
        a_struct[i]->raw = (char*)key;
        a_struct[i++]->count = (int)val;

    }

    size_t l = sizeof(a_struct) / sizeof(struct mystruct*);
    printf("%d",l); // outputs 1
}
Run Code Online (Sandbox Code Playgroud)

Car*_*rum 8

你做错了几件事.首先,您将获取sizeof(a_struct)指针的大小(因为它是什么a_struct),然后除以另一个指针的大小.保证1.

除此之外,你为什么要做分工呢?我认为你想要的是:

size_t l = sizeof(struct mystruct);
Run Code Online (Sandbox Code Playgroud)

要么

size_t l = sizeof(**a_struct);
Run Code Online (Sandbox Code Playgroud)

编辑:

我想我现在看到你分工的原因; 你正试图找到那个数组的大小.这不会起作用 - sizeof只能在C语言的编译时工作(在C99中有一些特殊的例外,它们不适用于你的代码),所以它无法弄清楚这样的动态数组的大小.