【问题标题】:Printing a struct in a struct in a linked list在链表中的结构中打印结构
【发布时间】: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->componentTypechar,但您需要 char * 才能使用 %s 打印,所以只需将其更改为 myInv->item.componentType 即可。

标签: c struct


【解决方案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 的内容,而只是指向相同的值。您要么需要每次分配一个新缓冲区并传递给stockItem_new,要么使用strdup 处理它

item->componentType = strdup(componentType);

这将分配足够的内存并复制componentType 的内容。您需要对将保留在结构中的任何字符串执行此操作(因为只复制地址!)。

【讨论】:

  • 感谢您的回答,另一个快速问题。我正在打印数据,出于某种原因,我为库存中的每个项目获得了相同的库存代码,但整数工作正常(价格、计数)有什么想法吗?我猜它与指针有关
  • 您每次都指向同一个缓冲区。在您的stockItem_new 中,您可以使用strdup 分配带有字符串副本的新存储空间。
  • 我不是用 stockItem *item = malloc(sizeof(stockItem));
  • 那是创建一个“空”项目。当您这样做item->componentType = componentType; 时,您指向与componentType 相同的东西,并且稍后会更改(由于读取文件等),然后它们全部都会更改。
  • 所以我需要对所有这些都使用 strdup 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-11
  • 2021-07-12
  • 2021-06-21
  • 2013-06-19
  • 2016-11-21
  • 2015-08-28
  • 2022-01-25
相关资源
最近更新 更多