简体   繁体   English

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

[英]Why are the values of a struct corrupted after the struct is initialized?

I am trying to initialize an array of structs with some values, but I cannot get the values to stay constant. 我正在尝试使用一些值初始化结构数组,但是我无法使这些值保持恒定。 I use an initial for loop to retrieve the values from a string and assign them to a struct in an array. 我使用一个初始的for循环从字符串中检索值,并将其分配给数组中的结构。 Once I try to iterate through that array with another loop, some of the values are not the same. 一旦尝试使用另一个循环迭代该数组,某些值将不相同。

This is the code in question: 这是有问题的代码:

    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");
    }

Here is the header file for an Order : 这是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

For example, the first loop would print: 例如,第一个循环将打印:

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

where as the second loop would give me: 第二个循环会给我什么:

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"

Why is are the values that I am initializing the struct with in the first loop getting overwritten in the second loop? 为什么在第一个循环中初始化结构的值在第二个循环中被覆盖? The title doesn't seem to be affected, but the rest of the parameters keep getting overwritten, and I'm not sure why. 标题似乎并没有受到影响,但是其余参数一直被覆盖,我不确定为什么。

strtok() returns pointers into the character buffer Line , which is overwritten later when fgets() is called the next time. strtok()将指针返回到字符缓冲区Line ,该缓冲区稍后在下次调用fgets()时被覆盖。

To save the "components" of the tokenized string, you can for example duplicate the strings with strdup() : 要保存标记化字符串的“组件”,例如,可以使用strdup()复制字符串:

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

You need to allocate memory for each of the data elements. 您需要为每个数据元素分配内存。 What you are doing is using the same memory area for your strings and just remembering pointers to those areas rather than using new memory areas for each string. 您正在做的事情是为字符串使用相同的存储区,只记住指向这些区域的指针,而不是为每个字符串使用新的存储区。

So you need to malloc() a new memory area for each of the records read in so that each record has its own unique memory area rather than all records sharing the same memory area. 因此,您需要为读入的每个记录malloc()一个新的存储区,以便每个记录都有其自己的唯一存储区,而不是所有共享相同存储区的记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM