2016-03-28 19 views
1

における構造体の構造体を印刷:私はこのような構造体を持っているリンクリスト

typedef struct stockItem { 
    char *componentType; 
    char *stockCode; 
    int numOfItems; 
    int price; 
} stockItem; 

// declaration 
stockItem *stockItem_new(char *componentType, char *stockCode, int numOfItems, int price); 

そして、多くの在庫のアイテムを格納するために、このような構造体(リンクリスト)

typedef struct inventory { 
    struct stockItem item; 
    struct inventory *next; 
}inventory; 

これらされています両方とも異なるヘッダーファイルにあります。

私はリンクリストを作成している、私はデータの特定のビットをオフに印刷したい、など:

void outputData(){ 

    // This temporarily takes the location of the structs in the 
    // linked list as we cycle through them to the end 

    struct inventory *myInv = pFirstNode; 

    printf("Current Inventory\n\n"); 

    // Until the ptr reaches a value of NULL for next we'll 
    // keep printing out values 

    while(myInv != NULL){ 
     // HERE IS MY PROBLEM HOW DO I PRINT OFF THE COMPONENTTYPE FROM THIS 
     printf("%s\n\n", myInv->item->compnentType); 
     // Switch to the next struct in the list 
     myInv = myInv->next; 
    } 
} 

EDIT:

stockItem *stockItem_new(char *componentType, char *stockCode, int numOfItems, int price){ 
    // creates a new duration for the song 
    stockItem *item = (stockItem*)malloc(sizeof(stockItem)); 

    // assigns the attributes 
    item->componentType = componentType; 
    item->stockCode = stockCode; 
    item->numOfItems = numOfItems; 
    item->price = price; 
    // returns it 
    return item; 
} 
+0

我々はCでmalloc' 'の結果をキャストしないでくださいstockItem_new' –

+0

Certaininly @AlterMann –

+0

'のコードを参照してくださいする必要があり、また、なぜあなたは「'(ポインタを返します)stockItem_new'あなたはドン場合はありますか'inventory'にポインタを置いていますか? (その宣言で 'item'は' stockItem'へのポインタではないので 'item.compnentType'となります)。 – crashmstr

答えて

1

我々は、残りのコードが表示されませんポインタを返す場合はstockItem_newなので、間違っています:

typedef struct inventory { 
    struct stockItem item; ///missing *! 
    struct inventory *next; 
} inventory; 

代わりに、宣言する必要がありますそれはよう:

typedef struct inventory { 
    struct stockItem *item; 
    struct inventory *next; 
} inventory; 

次に、あなたのstockItem_new機能をitemに割り当てることができ、あなたが期待するよう、あなたのoutputDataは動作します。

更新:あなたのstockItem_new 、あなたはcomponentTypeの内容のコピーを作成することが、ちょうど同じ値を指していません。あなたのいずれかがこれは十分なメモリを割り当てるとcomponentTypeの内容をコピーする新しいバッファを毎回割り当て、stockItem_newに渡したりstrdup

item->componentType = strdup(componentType); 

ているの世話をする必要があります。構造体に保持される文字列の場合は、これを行う必要があります(アドレスだけがコピーされるため!)。

+0

もう一つの簡単な質問私はデータを印刷していますが、何らかの理由でインベントリ内の各アイテムに対して同じ在庫コードが取得されていますが、intは何らかのアイデアを出していますか?ポインタ –

+0

毎回同じバッファを指しています。 'stockItem_new'では、[strdup](http://pubs.opengroup.org/onlinepubs/009695399/functions/strdup.html)を使って文字列のコピー – crashmstr

+0

私はstockItem * itemでそれをしていませんか? = malloc(sizeof(stockItem)); –

関連する問題