gpt4 book ai didi

c - 我的程序替换链表中所有节点中的所有字符串数据类型

转载 作者:太空宇宙 更新时间:2023-11-04 02:40:19 25 4
gpt4 key购买 nike

我有一个程序,主要是将历史记录(节点)添加到 employee_record(链表)。

这是我的代码:

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

struct history{
char *department1;
char *title1;
int day;
int month;
int year;
struct history *next;
};

struct employee_record{
char firstname[20];
char lastname[20];
long int employee_id;
char sex;
int age;
struct history *head;
};

void addjob(struct employee_record *rec,
char *department, char *title,
int day, int month, int year);

void print(struct employee_record *rec);

int main(int argc, char *argv[])
{
struct employee_record *worker=(struct employee_record*)malloc(sizeof(struct employee_record));
worker->head=NULL;
int c,d,e;
printf("Department\tTitle\tDay\tMonth\tYear\n");
while (1){
char a[10]=" ";
char b[10]=" ";
scanf("%s %s %d %d %d",a,b,&c,&d,&e);
addjob(worker,a,b,c,d,e);
printf("Department\tTitle\tDay\tMonth\tYear\n");
print(worker);
}
return 0;
}

void addjob(struct employee_record *rec,
char *department, char *title,
int day, int month, int year){
struct history *new=(struct history*)malloc(sizeof(struct history));
struct employee_record *temp;
new->day=day;
new->department1=department;
new->month=month;
new->year=year;
new->title1=title;
if (rec->head != NULL)
new->next=rec->head;
else {
new->next=NULL;
}
rec->head=new;
}

void print(struct employee_record *rec){
struct history *temp;
temp=rec->head;
printf("%s\t%s\t%d\t%d\t%d",temp->department1,temp->title1,temp->day,temp->month,temp->year);
while(temp->next!=NULL){
printf("\n");
temp=temp->next;
printf("%s\t%s\t%d\t%d\t%d",temp->department1,temp->title1,temp->day,temp->month,temp->year);
}
printf("\n");

}

但是,当我输入第二个条目时,前一个历史节点的部门和职位成员将被替换,但不会替换年月日,如下所示 All department and title gets replaced with most current input

为什么会这样?

最佳答案

scanf 将字符串存储在变量ab 中。然后将指向 ab 的指针传递给 addjob 函数。然后 addjob 函数将指针复制到结构中。该结构只有一个指向缓冲区的指针。它没有字符串的副本。下次调用 scanf 时,它会覆盖缓冲区的内容,并且会丢失第一个字符串。

解决方案是复制字符串,您可以通过三种方式完成

1) 将结构声明为

struct history{
char department1[10];
char title1[10];
...

然后使用strcpy将字符串复制到结构中。

2) 使用strdup 复制字符串

new->department1 = strdup(department);
new->title1 = strdup(title);

strdup 的问题:它是一个非标准函数,您必须在处理完字符串后释放内存。

3) 使用mallocstrcpy 复制字符串

new->department1 = malloc( strlen(department) + 1 );
strcpy( new->department1, department );
new->title1 = malloc( strlen(title) + 1 );
strcpy( new->title1, title );

这比 strdup 稍微多一些工作,但只使用标准函数。完成字符串后,您仍然需要释放内存。

关于c - 我的程序替换链表中所有节点中的所有字符串数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32664125/

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