【发布时间】:2021-03-31 01:06:00
【问题描述】:
我想编写一个使用链表的代码,从终端获取输入,然后打印出一个表格。
在这个例子中,我从元素表上传一些信息。
我收到分段错误。
有人可以帮我理解为什么吗?
#include <stdio.h>
#include <stdlib.h>
typedef struct element{
char name[20];
char symbol[20];
float atom_weight;
struct Element* next;
} element;
/* Add a new node to the top of a list */
element* insert_top(char name[20], char symbol[20], float atom_weight, element* head) {
element *new_element;
new_element = (element *) malloc(sizeof(element));
new_element->name[20] = name;
new_element->symbol[20] = symbol;
new_element->atom_weight = atom_weight;
new_element->next= head;
head = new_element;
printf("Top inserted");
return head;
}
element* table=NULL;
int main()
{
int choice=1, i=0;
char name[256];
char symbol[256];
float atom_weight;
printf("%d", choice);
while (choice!=0){
printf("\n Please enter element name:");
scanf("%s", name);
printf("\n Please enter element symbol:");
scanf("%s", symbol);
printf("\n Please enter atomic weight:");
scanf("%f", &atom_weight);
//printf("%s, %s,...Weight %f",name, symbol, atom_weight);
insert_top(name, symbol, atom_weight, table);
i=i+1;
printf("\nDo you want to continue (Y=1/N=0)? ");
scanf("%d", &choice); //You should add the space before %c, not after
}
printf("Out of cycle\n");
printf("Size of table %lu\n", sizeof(table));
printf("Weight %f",table->atom_weight);
while (table->next != NULL){
printf("\nElement: %s \t\t Symbol: %s \t\t Atomic weight: %f\n",table[i].name, table[i].symbol,table[i].atom_>
//printf("ciao");
table=table->next;
}
}
【问题讨论】:
-
很多事情在这里没有意义。您应该仔细阅读任何给定的 C 教科书中关于指针和数组的章节。
-
您从未将
main()中的table的值设置为NULL以外的任何值。鉴于您如何在main()末尾的while循环中使用它,我预计那里会出现段错误。 -
另外,鉴于您从不增加
i,您可以在main()底部的while循环中将所有table[i]替换为table->。 -
你从未初始化过的
temp有什么意义。我认为您想将其设置为table,然后在while循环中使用temp而不是table。 -
C 区分大小写
Element和element不是一回事
标签: c linked-list segmentation-fault