gpt4 book ai didi

c - 将项目添加到链表的末尾 segfault

转载 作者:行者123 更新时间:2023-11-30 16:32:14 24 4
gpt4 key购买 nike

struct vehicle *add_vehicle(struct vehicle *v){

struct vehicle *newcar = (struct vehicle*)malloc(sizeof(struct
vehicle));
scanf("%s", newcar->regnro);
scanf("%s", newcar->model);
newcar->next = NULL;
if(v->next == NULL){
v->next =newcar;
}
else{
struct vehicle *current = v;
while(current->next != NULL){
current = current->next;
}
current->next = newcar;
}
return v;
}

我正在尝试将车辆添加到列表末尾,但在第二次 scanf 后它给了我段错误,我不知道是我在循环中还是在 scanf 中犯了错误。我的结构是这样的:

    struct vehicle {
char regnro[7];
char *model;
struct vehicle *next;
};

最佳答案

首先,正如评论中其他人指出的那样 model是结构体的指针成员且未初始化。当你这样做时scanf("%s", newcar->model);它给出了段。过错。所以首先为其动态分配内存。例如

newcar->model = malloc(SIZE); /* define SIZE */

其次,你的成绩很正常struct vehicle变量为add_vehicle()方法所以无论做什么改变都是用 v 完成的在add_vehicle()不会影响main()方法。相反pass the addressstruct vehicle变量为add_vehicle()方法,在这种情况下,您不需要返回结构变量,因为它将通过引用调用。例如 main()方法调用看起来像

struct vehicle *head = NULL;
add_vehicle(&head);

以及 add_vehicle() 的定义看起来像

void add_vehicle(struct vehicle **v){
/* some code */
}

这是您可能需要的示例代码

void add_vehicle(struct vehicle **v){

struct vehicle *newcar = malloc(sizeof(struct vehicle));/* no need to type cast the result of malloc */
scanf("%s", newcar->regnro);
/* model is pointer member of dtruct, you need to do malloc for it */
newcar->model = malloc(SIZE)); /*define the size value */
scanf("%s", newcar->model);

newcar->next = NULL;
if((*v) == NULL){ /* first node */
newcar->next = *v; /* newnode next make it to head node */
(*v) = newcar; /*update the head node and */
return;
}
else{
struct vehicle *current = *v;
while(current->next != NULL){ /* move temp to the end node of list */
current = current->next;
}
current->next = newcar;/* add the new_node at last of the list */
}
}
void print_info(struct vehicle *temp) {
while(temp) {
printf("%s %s\n",temp->regnro,temp->model);
temp= temp->next;
}
}
int main(void) {
struct vehicle *head = NULL;
add_vehicle(&head); /* pass the address of head */
print_info(head);
return 0;
}

关于c - 将项目添加到链表的末尾 segfault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50235668/

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