我有以下問題:
對于作業,我應該逐行讀取 txt 檔案,使每一行成為鏈表中的一個元素,然后以正確的順序將它們列印出來。
如果我正確理解除錯器,我已經實作了這一點,但我的輸出看起來一團糟。我懷疑 nulltermination 是錯誤的,但這里的情況似乎并非如此(見下文)。輸出圖片
為了可讀性,我沒有寫出整個代碼,只是我認為是程式的重要部分。
#include <stdlib.h>
#include <stdio.h>
typedef struct node{
struct node *p;
char* string;
}node;
char *readline(FILE *stream)
//returns reference to string, returns NULL if EOF is reached before any char was read.
//If a line is EOF terminated it will return the string to the point where EOF was reached.
{
char *string = malloc(sizeof(char));
char c;
int len = 0;
if((c = getc(stream)) == EOF) return NULL;
do{
*(string len) = c;
len ;
realloc(string, (sizeof(char)*(len) 1));
if(c == '\n') break;
}while((c = getc(stream)) != EOF);
string[len] = '\0'; //make it nullterminated
return string;
}
node *new_node(FILE* stream)
// creates a new node from a line read by the readline() function.
{
node *new = malloc(sizeof(node));
new->string = readline(stream);
new->p = NULL;
return new;
}
void tail(node *newnode, node *head)
{
node *tmp = head;
while(tmp->p != NULL)
{
tmp = tmp->p;
}
tmp->p = newnode;
}
int main()
{
FILE *moby = fopen("testtxt.txt", "r");
if(moby == NULL) perror("FILE ERROR");
node *head = new_node(moby);
node *tmp;
//constructing the list
while((tmp = new_node(moby))->string != NULL)
{
tail(tmp, head);
}
//printing the list
while(1){
printf("%s", head->string);
if(head->p == NULL) break; //end of linked list is reached
head = head->p;
}
fclose(moby);
return 0;
}
特別是以下部分似乎對我構建“字串”的方式有問題:
while(1){
printf("%s", head->string);
if(head->p == NULL) break; //end of linked list is reached
head = head->p;
}
我的理解是,為了使 printf 與 %s 修飾符一起使用,字串必須以空字符結尾。我想我通過string[len] = '\0';除錯器向我展示的和我實作它的方式實作了這一點。除錯截圖。
此外,我讓除錯器將其解釋為一個陣列,以便我可以查看 '\0' 字符是否在我期望的位置,就是這種情況。除錯截圖。
現在我有點不知所措,因為我找不到這個問題的其他例子,除錯器似乎告訴我我正在生成正確的資料。
我希望我只是錯過了一個有人能夠發現的小細節。
TIA
(我用的是eclipse,win 10控制臺和eclipse控制臺的輸出是一致的)
uj5u.com熱心網友回復:
可能還有其他問題,但您的使用realloc是錯誤的。
這里
realloc(string, (sizeof(char)*(len) 1));
您需要保存回傳值,因為那是分配的記憶體所在的位置。
喜歡
char* temp = realloc(string, (sizeof(char)*(len) 1));
if (temp == NULL)
{
// add error handling
}
string = temp;
與所描述的問題無關:
當您想一直向串列末尾添加新元素時,通常最好使用tail指向最后一個元素的指標。這將使插入速度更快,因為您不需要while(tmp->p != NULL)回圈。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/393276.html
