2010-03-10 126 views
1

出于某种原因,如果我试图得到mystruct实际大小我不断收到尺寸1.大小在C结构的等于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 
} 
+2

此外,使用%zu代替size_t的%d格式说明符。 – 2010-03-10 19:34:57

+0

谢谢,解决了这个问题! – Josh 2010-03-10 19:35:30

回答

9

你正在做一些事情错了。首先,你正在使用sizeof(a_struct)这将是一个指针的大小(因为这是a_struct是),然后除以另一个指针的大小。保证1.

除此之外,你为什么做一个部门呢?我想你想的是:

size_t l = sizeof(struct mystruct); 

size_t l = sizeof(**a_struct); 

编辑:

我想我现在可以看到你的部门的原因;你正试图找到该数组的大小。这是行不通的 - sizeof只能在C编译时工作(在C99中有一些特殊的例外,不适用于你的代码),所以它不能计算出这样的动态数组的大小。

+1

“'sizeof'只能在编译时在C中工作......”在C99中不完全正确,因为在C99中'sizeof'可以与VLA一起使用,在这种情况下它可以在运行时工作。 – AnT 2010-03-10 19:55:00

+0

@AndreyT,很好的电话。这不适用于OP代码的动态数组从malloc方法。 – 2010-03-10 19:58:53

4

你被一个指针的大小除以指针的大小。

1

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

这两个尺寸都是一样的。

难道这size_t l = sizeof(struct mystruct);

1

你正在服用两个指针的大小,将一个由其他

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的所有值的总和。