gpt4 book ai didi

c - 尝试打印结构时出现段错误

转载 作者:行者123 更新时间:2023-11-30 14:34:38 27 4
gpt4 key购买 nike

我正在尝试编写一个代码,允许用户输入他想要的任意数量的条目,然后将它们打印出来(以及其他功能,仍然需要实现)。但是当我尝试启动代码时,它允许我输入条目,但是当我想打印它们时,它不会注册 current.namecurrent.telNo (仅打印出 1: has tel. No. ),并在其后出现段错误。知道我该如何解决这个问题吗?

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

int listSize;
int counter = 0;

struct Entry {
char name[20];
char telNo[9];
struct Entry *next;
} current;

int main()
{
struct Entry *linkedList = (struct Entry * )malloc(sizeof(struct Entry));
struct Entry *current = linkedList;
first(current);
print(current);
return 0;
}

void first(struct Entry linkedList)
{
int i;
printf("enter list size: ");
scanf("%d", &listSize);
printf("Now enter entries one by one: \n");
for (i = 0; i < listSize; i++) {
counter++;
printf("Name: ");
scanf("%s", linkedList.name);
printf("Telephone: ");
scanf("%s", linkedList.telNo);

if (i != listSize -1) {
linkedList.next = (struct Entry *)malloc(sizeof(struct Entry));
linkedList = *linkedList.next;
} else {
linkedList.next = NULL;
}
}
}

void print(struct Entry linkedList)
{
int nr = 1;
printf("\nTelephone book is:\n");
while (current.name != NULL) {
printf("%d: %s has tel. No.\t%s\n", nr, current.name, current.telNo);
current = *current.next;
nr++;
}
}

最佳答案

而不是 .您应该使用 -> 并且在您的 print() 中您正在遍历 current 而不是 linkedList ,这导致问题。此外,您的函数定义应该在其使用之前。请检查下面的代码片段,我已经做了相应的更改。

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

int listSize;
int counter = 0;

struct Entry {
char name[20];
char telNo[9];
struct Entry *next;
} current;


void print(struct Entry *linkedList)
{
int nr = 1;
printf("\nTelephone book is:\n");
while (linkedList->name != NULL) {
printf("%d: %s has tel. No.\t%s\n", nr, linkedList->name, linkedList->telNo);
linkedList = linkedList->next;
nr++;
}

}
void first(struct Entry *linkedList)
{
int i;
printf("enter list size: ");
scanf("%d", &listSize);
printf("Now enter entries one by one: \n");
for (i = 0; i < listSize; i++) {
counter++;
printf("Name: ");
scanf("%s", linkedList->name);
printf("Telephone: ");
scanf("%s", linkedList->telNo);

if (i != listSize -1) {
linkedList->next = (struct Entry *)malloc(sizeof(struct Entry));
linkedList = linkedList->next;
} else {
linkedList->next = NULL;
}
}
}

int main()
{
struct Entry *linkedList = (struct Entry * )malloc(sizeof(struct Entry));
struct Entry *current = linkedList;
first(current);
print(current);
return 0;
}

关于c - 尝试打印结构时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58892889/

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