gpt4 book ai didi

c - 如何给结构体中的字符指针赋值并以队列的形式存储

转载 作者:行者123 更新时间:2023-11-30 16:06:20 26 4
gpt4 key购买 nike

这是我的代码在队列中插入字符后,如果我弹出元素,字符(名称和优先级)将显示我输入的最新数据,以前的数据将被删除。

#include <stdio.h> 
#include <stdlib.h>
#include <string.h>

int NAME = 20;
int num = 1001;

typedef struct patient {
int age;

char *name;
char *priority;

struct patient* next;

} Patient;

Patient* newPatient(int age, char *p, char *name)
{
Patient* temp = (Patient*)malloc(sizeof(Patient));
temp->age = age;
temp->priority = p;
temp->next = NULL;
temp->name = name;
//strcpy(temp->name,name);
printf("name is%s",temp->name);
printf("priority is%s",temp->priority);

return temp;
}

void addPatient(Patient** head, int age, char *p, char *name)
{
Patient* start = (*head);
Patient* temp = newPatient(age, p, name);

if (atol((*head)->priority) < age) {

temp->next = *head;
(*head) = temp;
}
else {

while (start->next != NULL &&
atol(start->next->priority) < age) {
start = start->next;
}

temp->next = start->next;
start->next = temp;
}
}

我是编码新手,请帮助我

最佳答案

问题出在 Patient* newPatient(intage, char *p, char *name) 中:您没有为 priorityname 分配新内存。要么总是为 pname 传递新分配的内存,该内存由 priorityname 指向,或者在 newPatient() 中为 priorityname 分配新内存,然后执行 strcpy()

关于c - 如何给结构体中的字符指针赋值并以队列的形式存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59998036/

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