2010-08-25 54 views
0

當我嘗試printf()數據的值時,我什麼也沒得到,但是如果我要做date = "text"那會起作用。任何人都知道這個的原因?C語言:結構體和字符數組

struct aac { char **data; }; 

int main () { 
    char* value = malloc (100); 
    strcpy (value, "test"); 
    struct aac b; 
    b.data = malloc (100); 
    cake (value, &b); 
    donut (&b); 
    return 0; 
} 

int cake (char *value, struct aac *c) { 
    c->data[0] = value; 
    return 0; 
} 

int donut (struct aac *b) { 
    printf ("%s", b->data[0]); 
    return 0; 
} 
+0

你的榜樣的當前版本(#4)對我來說工作得很好。你在'cake()'函數的'value'參數中加了'char *'後是否嘗試過? – MatthewD 2010-08-25 03:27:19

+0

是的,我試圖重建問題時犯了一個錯誤。 – Jay 2010-08-25 03:50:04

+0

這個代碼版本不工作;缺少蛋糕和甜甜圈原型 – user411313 2010-08-25 11:39:44

回答

0

也許這個例子可能會有幫助:

#include <stdio.h> 
#include <string.h> 
#include <malloc.h> 
#include <errno.h> 

struct aac { 
    char **pastries; 
}; 

void 
init_pastries (struct aac * rec_p, int max) 
{ 
    /* Allocate space for max #/pastries, plus a NULL delimiter */ 
    int nbytes = sizeof (char *) * (max+1); 
    rec_p->pastries = (char **)malloc (nbytes); 
    memset (rec_p->pastries, 0, nbytes); 
    printf ("init_pastries: max #/pastries: %d, malloc: %d bytes...\n", 
    max, nbytes); 
} 

void 
add_pastry (char * name, int i, struct aac *rec_p) 
{ 
    int nbytes = strlen (name) + 1; 
    rec_p->pastries[i] = (char *)malloc (nbytes); 
    strcpy (rec_p->pastries[i], name); 
    printf ("add_pastry (%s): malloc= %d bytes...\n", 
    name, nbytes); 
} 

void 
print_pastries (struct aac * rec_p) 
{ 
    char **s = NULL; 
    for (s = rec_p->pastries; (*s); s++) 
    printf ("pastry: %s...\n", *s); 
} 

int 
main () { 
    struct aac rec; 
    init_pastries (&rec, 5); 
    add_pastry ("cake", 0, &rec); 
    add_pastry ("donut", 1, &rec); 
    print_pastries (&rec); 
    return 0; 
} 

這裏的示例輸出:

gcc -o tmp tmp.c 

./tmp 
    init_pastries: max #/pastries: 5, malloc: 24 bytes... add_pastry 
    (cake): malloc= 5 bytes... add_pastry 
    (donut): malloc= 6 bytes... pastry: 
    cake... pastry: donut... 

「希望幫助......至少有點:)

+0

我不知道我在看什麼。謝謝,因爲它完美地工作,我將不得不對此進行審查。 – Jay 2010-08-25 03:31:05

+0

嗨 - 我不確定你的問題到底是什麼,所以我舉了一個例子來說明我認爲你可能不清楚的一些事情。 我希望至少有一些例子對你有用。 無論如何,請在找到解決方案時回覆,並且請將問題標記爲「已解決」 – paulsm4 2010-08-25 05:30:46

0

如果您將char *添加到值,它對我來說工作正常。沒有這個,我認爲這是隱式的int。這從C99中刪除。即使它不是,你應該顯然不會通過一個整數char *。此外,我不知道你是否允許混合隱式int和顯式類型(struct aac *)。

另一個問題是你的第二個malloc不可移植。在32位機器上,它將分配25個指針,但在64位12.5上,這是沒有意義的。使用類似於:

b.data = malloc (sizeof(char *) * 25); 

您可能希望將25聲明爲某個常量。

+0

它打印出你的價值? – Jay 2010-08-25 02:51:04