c-如何避免链表的分段错误



我想制作一个使用链表的代码,从终端获取输入,然后打印出一个表。

在这个例子中,我正在从元素表上传一些信息。

我得到分割错误。

有人可以帮我理解为什么?

#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 cyclen");
printf("Size of table %lun", sizeof(table));
printf("Weight %f",table->atom_weight);

while (table->next != NULL){
printf("nElement: %s tt Symbol: %s  tt Atomic weight: %fn",table[i].name, table[i].symbol,table[i].atom_>
//printf("ciao");
table=table->next;
}
}

您需要使用strcpy复制字符串,请参阅insert_top未定义Element,应为element。次要不强制转换malloc结果。

仍然存在一些问题,字符大小限制,需要检查scanf返回代码。

最后需要释放malloc内存。

#include <stdio.h>
#include <stdlib.h>
#include <string.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 = malloc(sizeof(element));
strcpy(new_element->name, name);
strcpy(new_element->symbol, symbol);
new_element->atom_weight = atom_weight;
new_element->next= head;
printf("Top inserted");
return new_element;
}
int main()
{
element* table=NULL;
int choice=1;
printf("%d", choice);
while (choice!=0){
char name[256];
char symbol[256];
float atom_weight;
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);
table = insert_top(name, symbol, atom_weight, table);
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 cyclen");

for (element *e = table; e; e = e->next) {
printf("nElement: %s tt Symbol: %s  tt Atomic weight: %fn",
e->name, e->symbol, e->atom_weight);
}          
return 0;  
}

相关内容

  • 没有找到相关文章

最新更新