2010-03-10 125 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的所有值的總和。