所以我有這個程序,我把頭從頭放在一起c。它來自第6章 - 數據結構章節......我的問題是輸出顯示了所有以前列出的條目以及最後輸入的標準輸入名稱。所以相反,當程序打印幾乎所有東西時,顯示一切打印出來我很難形容。如果你只是複製並粘貼到你的機器上的文本編輯器並運行代碼,你會明白我的意思。c程序不按預期輸出
這本書展示了使用<重定向工具獲取島名文件的程序。當我嘗試這個時,它打印第一個名字的第二個名字和第一個名字。然後是下一個名字和第二個名字......然後是下一個名字和第三個,第二個和第一個名字......等,取決於有多少名字。在標準輸入中的終端中輸入文本時也會發生此行爲。
如果我更改了代碼說顯示器(下)它的工作原理接近我所期望的,但它仍然打印出一個額外的空白行,有可能是內存泄漏
此代碼是相當多了我的頭可以找出爲什麼它是這樣打印?
我會先問c討論板的頭部,但我想先問stackoverflow並立即得到答案。
我的代碼如下。如果您將其複製並粘貼到文本編輯器中,它不應該看起來像一堵文字牆。
快樂編碼。
#include <stdio.h> // basic input output
#include <stdlib.h> // for obtaining and releasing heap memory malloc and free...
#include <string.h> // for the stringdup method
typedef struct island {
char *name;
char *opens;
char *closes;
struct island *next;
} island;
void display(island *madonna);
island* create(char *name);
void release(island *start);
int main()
{
/* create islands */
island *start = NULL;
island *i = NULL;
island *next = NULL;
char name[80];
puts("enter island name...");
for(; fgets(name, 80, stdin) != NULL; i = next) {
next = create(name);
if(start == NULL)
start = next;
if (i != NULL)
i -> next = next;
display(start);
}
release(start);
}
// display method
void display(island *start)
{
island *i = start;
if (i == NULL)
puts("i equals NULL ");
for(;i != NULL; i = i ->next) {
printf("Name: %s open: %s-%s\n", i->name, i->opens, i->closes);
}
}
// create method
island* create(char *name)
{
island *i = malloc(sizeof(island));
i->name = strdup(name);
i->opens = "09:00";
i->closes = "17:00";
i->next = NULL;
return i;
}
// release method
void release(island *start)
{
island *i = start;
island *next = NULL;
for(; i != NULL; i = next) {
next = i-> next;
free(i->name); // must free this first because of strdup uses heap memory
free(i);
}
}
你需要做'display(i);'而不是'display(start);' – 2013-05-06 05:25:49
...或者將'display()'移到循環之外。 – WhozCraig 2013-05-06 05:27:52
我不能相信有人標記了這個問題。無論如何感謝迄今爲止的幫助。 @WhozCraig如果我將display()從循環中移出,程序只是在那裏進行輸入,但實際上並沒有顯示任何內容...... – 2013-05-06 05:33:52