我試圖創建一個單一的鏈接列表,其中包含我的桌面上的.txt文件的一些單詞,但是當我在終端運行它,我得到了分段錯誤。後來我編譯Xcode的代碼並運行它,我得到了這個錯誤信息: 線程1:EXC_BAD_ACCESS(代碼= 1,地址= 0x7fff5fc00000) 我是一個初學者,現在我真的需要一些幫助。謝謝!在我的C程序需要一些幫助,我有一個分段錯誤,但我不知道爲什麼
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct word{
int num;
char word[50];
struct word *next;
} Word;
#define len sizeof(Word)
Word *create();
void print(Word *head);
int main()
{
Word *head;
head = create();
print(head);
return 0;
}
Word *create()
{
Word *head, *p1, *p2;
char word[50], c;
int i = 0;
FILE *fp = fopen("/Users/apple/Desktop/words", "r");
head = p1 = p2 = NULL;
while(fp != NULL){
i = 0;
p1 = (Word *)malloc(len);
//get the English word
while((c = fgetc(fp)) != '\n'){
word[i++] = c;
}
word[i] = '\0';
strcpy(p1->word, word);
p1->next = NULL;
if(head == NULL){
head = p1;
p2 = p1;
} else {
p2->next = p1;
p2 = p1;
}
p1 = p1->next;
}
return head;
}
void print(Word *head)
{
Word *p = head;
while(p != NULL){
printf("%s\n", p->word);
p = p->next;
}
}
這是.txt文件的內容:
歡迎來到SO。我強烈建議花一些時間學習如何使用調試器。這是弄清楚你的問題的第一步。 – OldProgrammer
請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。 SO不是調試服務。一旦你找出問題所在,如果你不知道爲什麼*這是一個問題,那麼一定要問一個問題。 – StoryTeller
通過使用調試器來捕捉動作中的崩潰,因此您可以在您的代碼中找到* where *發生的位置。然後當你知道,並且仍然在調試器中時,檢查所有涉及變量的值,以確保它們看起來沒問題。至少請給我們*這些信息(位置和價值)。 –