【问题标题】:size of a struct in c equals to 1c中结构的大小等于1
【发布时间】:2010-03-10 19:26:55
【问题描述】:

出于某种原因,如果我尝试获取 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
}

【问题讨论】:

  • 另外,对 size_t 使用 %zu 而不是 %d 格式说明符。
  • 谢谢,问题解决了!

标签: c struct


【解决方案1】:

你做错了几件事。首先,您将采用sizeof(a_struct),它将是一个指针的大小(因为这就是a_struct 的大小),然后除以另一个指针的大小。保证1。

除此之外,您为什么要进行除法?我认为你想要的是:

size_t l = sizeof(struct mystruct);

size_t l = sizeof(**a_struct);

编辑:

我想我现在明白你们分裂的原因了;您正在尝试查找该数组的大小。那是行不通的——sizeof 只能在 C 中的编译时工作(C99 中有一些特殊的例外情况不适用于您的代码),因此它无法计算出这样的动态数组的大小。

【讨论】:

  • "sizeof 只能在 C 编译时工作"...在 C99 中不完全正确,因为在 C99 中 sizeof 可以与 VLA 一起使用,在这种情况下它可以在运行时工作-时间。
  • @AndreyT,好电话。不过,这不适用于 OP 代码的 dynamic-array-from-malloc 方法。
【解决方案2】:

您将指针的大小除以指针的大小。

【讨论】:

    【解决方案3】:

    a_struct 是一个指向 struct mystruct 的双指针。
    struct mystruct * 是一个指向 struct mystruct 的指针。

    两者的尺寸相同。

    这样做size_t l = sizeof(struct mystruct);

    【讨论】:

      【解决方案4】:

      您正在获取两个指针的大小,然后将一个除以另一个,

      size_t l = sizeof(a_struct) / sizeof(struct mystruct*);
      

      a_struct 被声明为struct mystruct **a_struct 所以这和说的一样

      size_t l = sizeof(struct mystruct **) / sizeof(struct mystruct*);
      

      由于所有指针的大小相同,** 与 * 的大小相同,所以它的计算结果始终为 1。

      我不太确定您要在这里打印什么,a_struct 的大小?或总分配大小? a_struct 的大小只是 c.total,总分配是您传递给 malloc 的所有值的总和。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-17
        • 1970-01-01
        • 1970-01-01
        • 2017-07-15
        • 1970-01-01
        • 1970-01-01
        • 2010-12-22
        • 1970-01-01
        相关资源
        最近更新 更多