gpt4 book ai didi

c - 这段代码有什么问题?

转载 作者:太空宇宙 更新时间:2023-11-04 08:47:29 24 4
gpt4 key购买 nike

我需要以下代码的帮助。

typedef struct orders
{
int quantity;
char foodname[50];
} ORDER;

ORDER *ptr;

typedef struct Table
{
int tableno;
int priority;
ORDER *orders;
struct Table *next;
} TABLE;

TABLE *head, *s;
int n = 0;

int insert(int tablenum, int prio, char foodname[], int qty)
{
TABLE *newO, *temp, *temp2;
newO = (TABLE*)malloc(sizeof(TABLE));
newO->tableno = tablenum;
newO->priority = prio;
strcpy(newO->orders->foodname, foodname);
newO->orders->quantity = qty;
//more code here...
}

在该程序的主要功能中,将询问用户要点的 table 号、优先级、他们要点的食物的名称以及他们要点的食物的数量。

这段代码还有一个显示列表函数,它会从优先级最高到最低的顺序打印出列表中的所有数据。

现在我的问题是,例如我已经有两个不同的交易,发生的情况是我的第二个交易复制了我的第一个交易的“食物名称”和“数量”。

请大家帮帮我。

最佳答案

TABLE *newO = (TABLE*)malloc(sizeof(TABLE));

TABLE 分配内存,但不为 orders 分配内存,在 malloc 调用之后它只是一个未初始化的指针,所以这一行:

newO->orders->quantity = qty;

调用一个未定义的行为。您还需要为订单分配内存,例如:

TABLE *newO = (TABLE*)malloc(sizeof(TABLE));
newO->orders = (ORDER*)malloc(10*sizeof(ORDER));
...
newO->orders[0]->quantity = qty;

...尽管老实说,很难判断 orders 是否真的应该是一个数组。

关于c - 这段代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21127232/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com