【发布时间】:2015-12-29 11:11:08
【问题描述】:
这是我正在使用的一段代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int wordlen = 4;
typedef struct Node
{
char* word;
struct Node* next;
struct Node* prev;
}node;
node* head;
node * getWord(char* x)
{
node* newNode = malloc(sizeof(node));
newNode->word = x;
newNode->next = NULL;
newNode->prev = NULL;
return newNode;
}
void insertion(char* x)
{
node* temp = head;
node* newNode = getWord(x);
if (head == NULL)
{
head = newNode;
return;
}
while(temp->next != NULL)
temp = temp->next;
temp->next = newNode;
newNode->prev = temp;
}
void print()
{
node* temp = head;
while (temp != NULL)
{
printf("%s", temp->word);
temp = temp->next;
printf(" ");
}
printf("\n");
}
void sort()
{
char* a = malloc((wordlen + 1)*sizeof(char));
char* b = malloc((wordlen + 1)*sizeof(char));
node* temp = head;
while (temp != NULL)
{
a = temp->word;
temp = temp->next;
b = temp->word;
if (a[0] < b[0])
{
//temp->word = a;
//temp = temp->prev;
//temp->word = b;
}
}
}
int main(int argc, char *argv[])
{
insertion("asdk");
insertion("mapa");
insertion("klop");
sort();
print();
return 0;
}
分段错误出现在 sort() 函数中,尤其是在变量 b 中。
我想到的是当指针到达 NULL 时,当我试图返回(使用 prev 指针)我收到错误,因为我无权访问该特定内存块。
一旦我完全遍历了链表的最后一个节点,我该如何再次访问它?
【问题讨论】:
-
您可以通过维护尾指针和头指针来访问最后一个节点。您甚至可以将它们保存在
node结构中,这样您就只有一个与列表关联的变量。
标签: c linked-list segmentation-fault