2012-11-18 60 views
4

我創建了一個名爲「mcguffins」的結構數組,我得到了一個非常奇怪的錯誤。C指針沒有正確分配

//prints the info in a mcguffin 
    void printInfo(int i,struct mcguffin * new) { 
     printf("%d \tNum: %d\t Word: %s\n", i, new->num, new->word); 
    } 

    //creates a new mcguffin 
    struct mcguffin * addMG(int n, char * w) { 
     printf("Expected output:\n\tNum: %d\tWord: %s\n", n, w); 
     struct mcguffin * new; 
     new = malloc(sizeof *new); 
     new->num = n; 
     strncpy(new->word, w, sizeof(char[20])); 
     printf("Actual output: \n\t"); 
     printInfo(1, new); 
     return new; 
    } 

//creates a list of mcguffin pointers, and sets these pointers to new mcguffins 
struct mcguffin ** writeList() { 
    struct mcguffin ** list = malloc(10 * sizeof(*list)); 
    list[0] = addMG(2, "Jeter"); 
    list[1] = addMG(14, "Granderson"); 
    list[2] = addMG(25, "Teixeira"); 
    list[3] = addMG(13, "Rodriguez"); 
    list[4] = addMG(24, "Cano"); 
    list[5] = addMG(33, "Swisher"); 
    list[6] = addMG(55, "Martin"); 
    list[7] = addMG(20, "Posada"); 
    list[8] = addMG(11, "Gardner"); 
    list[9] = addMG(42, "Mo"); 
    return list; 
} 

出於某種原因,列表[0]和列表[1]沒有被分配給所創建的結構體,但是列表[2]通過表[9]是。 addMG工作正常,並且爲列表[0]和列表[1]創建結構,但由於某些原因,當我嘗試在它們上使用printInfo時,而不是在結構上打印信息時,它會打印出一個內存地址, >數字應該去,並打印出什麼新的 - >單詞。

0 Num: 30519472 Word: 
1 Num: 30519600 Word: 
2 Num: 25 Word: Teixeira 
3 Num: 13 Word: Rodriguez 
4 Num: 24 Word: Cano 
5 Num: 33 Word: Swisher 
6 Num: 55 Word: Martin 
7 Num: 20 Word: Posada 
8 Num: 11 Word: Gardner 
9 Num: 42 Word: Mo 

這可能是一些愚蠢的錯誤,因爲我是新的C,但任何幫助,將不勝感激。

編輯:爲了澄清,mcguffins聲明在一個單獨的頭文件,像這樣:

struct mcguffin { 

    int num; 
    char word[20]; 
}; 

回答

2
new = (struct mcguffin *)malloc(sizeof(struct mcguffin *)); 
                 ^^ 

你的指針麥高菲分配足夠的空間。丟掉*。更好的是,將其更改爲:

new = malloc(sizeof *new); 

您的list分配同樣是錯誤的。您應該分配:

struct mcguffin **list = malloc(10 * sizeof *list); 
+0

我已經相應改變的代碼,但我仍然得到真正奇怪的錯誤還有什麼地方都被賦予不同的列表[0]和list [1]。 – user1834200

+0

@ user1834200如何聲明'mcguffin'? – cnicutar

+0

它被聲明在一個單獨的頭文件中,如下所示: struct mcguffin { int num; char word [20]; }; 這是我必須使用作爲我給予的任務的一部分,所以我不能改變任何事情。 – user1834200