0
我想在C中實現一個鏈表。我相信我正在創建並插入元素,但每次嘗試循環時都會出現分段錯誤。這裏是我的鏈表代碼:穿越鏈表時的分段錯誤
struct node {
char **data;
struct node *next;
};
兩個全局變量來存儲指針頭和尾:
struct node *head;
struct node *tail;
代碼中插入一個元素:
void insert(char **args)
{
struct node* pointer = (struct node*)malloc(sizeof(struct node));
pointer -> data = args;
pointer -> next = NULL;
if(head == NULL) {
head = pointer;
tail = pointer;
}
else {
tail -> next = pointer;
tail = pointer;
}
}
然後我試着通過列表並打印數據內容(這成功地打印列表中的元素,但是隨後出現分段錯誤):
int print_list(char **args)
{
struct node *curPointer = head;
if(curPointer == NULL) {
printf("%s", "List is empty\n");
}
else {
printf("%s", "List: ");
do {
int i;
while(curPointer->data[i] != NULL) {
printf("%s", tail->data[i]);
i++;
}
printf("%s", "\n");
curPointer = curPointer->next;
}while(curPointer->next != NULL);
}
return 1;
}
我的程序中依賴循環遍歷列表的其他函數有類似的分段錯誤問題。使用沒有初始化
注意:他們說[你不應該在C]中輸入'malloc()'的結果(http://stackoverflow.com/questions/605845/do-i-cast-the-result-of -malloc)。 – MikeCAT
建議您使用調試器來幫助您找到問題。 – kaylum
警告:在函數'insert()'中不使用參數'char ** data' – MikeCAT