[英]Why is my C program not printing anything sometimes from the string inconsistantly? (using linked lists)
我正在嘗試使用鏈表來存儲元素周期表中的數據。 名稱、符號和原子量。 我的代碼可以正確打印某些元素,但有時元素名稱會消失。 多次運行相同的代碼,它不會在不同的時間打印不同的名稱。 (我在輸入時弄亂了順序,但請忽略它。)
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include <string.h>
typedef struct list{char element[20]; char sym[20];float weight;struct list*next;}list;
int printlist(list *h, char *title){
printf("%s\n", title);
while(h!=NULL){
printf("%s: %s: %f \n", h->element, h->sym, h->weight);
h = h-> next;
}
}
list* create_list(char e[], char s[], float w){
list * head = malloc(sizeof(list));
strcpy(head->element,e);
strcpy(head -> sym,s);
head -> weight = w;
head -> next = NULL;
return head;
}
void add_to_rear(char e[], char s[], float w, list*h){
while(h->next != NULL){
h= h-> next;
}
list *nn = create_list(e, s, w);
h -> next = nn;
}
int main(){
list list_of_atoms;
list * head = NULL;
for(int i=0; i<1;i++){
printf("element %d", i+1);
char el[20];
char symbol[2];
float atwt;
scanf("%s", el);
scanf("%s", symbol);
scanf("%f", &atwt);
head = create_list(el, symbol, atwt);
}
for(int i=1; i<10;i++){
printf("element %d", i+1);
char el[20];
char symbol[2];
float atwt;
scanf("%s", el);
scanf("%s", symbol);
scanf("%f", &atwt);
add_to_rear(el, symbol, atwt, head);
}
printlist(head, "First 10 elements");
return 0;
}
你分配並填充一堆list
(這是一個用詞不當;每個結構實際上是關於一個元素的信息)然后丟棄它們...... head
最終指向輸入的最后一個元素,它的next
字段是NULL
。 然后你再次讀入所有元素(為什么?),每次掃描到列表的末尾並附加元素——這是一個 O(N*N) 操作。 (我懷疑您實際上為第一個循環輸入了一個空列表,然后為第二個循環輸入了 10 個元素,但無法判斷,因為您提供的輸入是截斷的屏幕截圖。請不要這樣做。相反, 從你的 CMD 窗口復制文本。) 編輯:現在我看到你的第一個循環實際上只運行一次。 就像您以一種方式編寫它,然后改變主意並以另一種方式編寫它,但將舊代碼留在那里。
輸出錯誤的原因是您使用scanf
將 2 個字符的符號和終止 NUL讀取到symbol[2]
,這還不夠大。 這是未定義的行為,但它可能正在做的是用 NUL 覆蓋元素名稱的第一個字節。 請注意,所有帶有 2 個字母符號的元素都缺少元素名稱,而帶有 1 個字母符號的元素則沒有。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.