结构初始化后,为什么结构的值被破坏了?

时间:2014-04-19 20:07:24

标签: c arrays struct

我正在尝试用一些值初始化一个结构数组,但我无法让值保持不变。我使用一个初始for循环来从字符串中检索值并将它们分配给数组中的结构。一旦我尝试用另一个循环迭代该数组,一些值就不一样了。

这是有问题的代码:

    void printOrder(Order *node)
    {
         printf("Title is: %s\n",node->title);
         printf("Price is: $%f\n",node->price);
         printf("ID is: %d\n",node->custID);
         printf("Category is: %s\n",node->category);
    }

    void initOrder(Order *newOrder, char *title, double price, int custID, char   *category)
    {
         newOrder->title = title;
         newOrder->price = price;
         newOrder->custID = custID;
         newOrder->category = category;
         newOrder->next = NULL;

         printf("new order object initialized\n");
    }

    char *title;
    char *priceTemp;
    char *idTemp;
    char *category;

    Order localOrders[numOrders]; // numOrders is a value found earlier

    int k;
    for(k = 0; k < numOrders; k++)
    {

            fgets(Line,orderLineSize,orders); // orderLineSize was found earlier


            title = strtok(Line,"|");
            priceTemp = strtok(NULL,"|");
            idTemp = strtok(NULL,"|");
            category = strtok(NULL,"|");

            price = atof(priceTemp);
            id = atoi(idTemp);

            localOrders[k].title = title;
            localOrders[k].price = price;
            localOrders[k].custID = id;
            localOrders[k].category = category;

            Order *temp = &localOrders[k];

            initOrder(temp,title,price,id,category);
            printOrder(temp);
    }
    Order *temp;

    for(k = 0; k < numOrders; k++)
    {
            temp = &localOrders[k];
            printOrder(temp);
            printf("\n");
    }

以下是Order的标头文件:

#ifndef ORDER_H
#define ORDER_H
#include <stdlib.h>
struct Order {
    char *title;
    double price;
    int custID;
    char *category;

    struct Order *next;
};

typedef struct Order Order;

void initOrder(Order *newOrder, char *title, double price, int custID, char *category);
void printOrder(Order *node);

#endif

例如,第一个循环将打印:

Title is: "Tasting Beer: An Insider's Guide to the World's Greatest Drink"
Price is: $11.310000
ID is: 5
Category is: HOUSING01

第二个循环会给我:

Title is: "Tasting Beer: An Insider's Guide to the World's Greatest Drink"
Price is: $19.800000
ID is: 2
Category is: s Guide to the World's Greatest Drink"

为什么在第一个循环中初始化struct的值会在第二个循环中被覆盖?标题似乎没有受到影响,但其余的参数一直被覆盖,我不确定原因。

2 个答案:

答案 0 :(得分:1)

strtok()返回指向字符缓冲区Line的指针,稍后会覆盖它 下次调用fgets()时。

要保存标记化字符串的“组件”,您可以使用strdup()复制字符串:

title = strdup(strtok(Line,"|"));
// ...

答案 1 :(得分:0)

您需要为每个数据元素分配内存。你正在做的是为字符串使用相同的内存区域,只记住指向这些区域的指针,而不是为每个字符串使用新的内存区域。

因此,您需要为每个读入的记录malloc()一个新的内存区域,以便每条记录都有自己唯一的内存区域,而不是共享相同内存区域的所有记录。