【发布时间】:2016-03-28 16:36:20
【问题描述】:
我有一个这样的结构:
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;
}
}
编辑:
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;
}
【问题讨论】:
-
我们需要看
stockItem_new的代码 -
当然是@AlterMann
-
不要在C中转换
malloc的结果,如果你不在inventory中保留一个指针,为什么你有一个stockItem_new(它返回一个指针)? (使用该声明,它将是item.compnentType,因为item不是指向stockItem的指针)。 -
我在存货之前制作了 stockItem,所以我想我并没有提前考虑。你是什么意思不要在c中转换malloc的结果? @crashmstr
-
当您尝试编译问题中的代码时,编译器会告诉您什么?
myInv->item->componentType是char,但您需要char *才能使用%s打印,所以只需将其更改为myInv->item.componentType即可。