【发布时间】:2014-04-26 15:57:17
【问题描述】:
我正在使用 C 语言,试图传递链表列表的引用,但是当我编译和运行我的代码时,我在打印值时遇到了分段错误。
这些是我的结构:
typedef struct node_{
int value;
/*struct node_ next;*/
struct node_ *next; /*1) This needs to be a pointer to a node*/
}Node;
typedef Node* List;
我的函数原型:
int create_list(List*, FILE*);
void print_list(List*, int);
Node* new_node(int);
我的函数调用:
int length = create_list(array, fp);
printf("Pre Sort\n");
print_list(array, length);
我正在使用的功能:
int create_list(List* array, FILE* fp){
int length, i, index, value;
fscanf(fp, "%d", &length);
//array = malloc(sizeof(Node));
array = malloc(sizeof(List));
for(i = 0; i < length; i++)
{
//(*array)[i] = NULL;
array[i] = NULL;
}
while(!feof(fp)){
fscanf(fp, "%d %d", &index, &value);
Node* node = new_node(value);
node->next = array[index];
array[index] = node;
}
}
/*Creates a new node of type Node, sets node->value = value and returns it. */
Node* new_node(int value){
Node* node;
node = malloc(sizeof(Node));
node->value = value;
node->next = NULL;
return node;
}
/*For each index in the array, print the index, the linked list it points to,
* and the sum of its nodes. See the sample output for an example.*/
void print_list(List* array, int length){
int i;
for(i = 0; i < length; i++){
Node* curr = array[i];
printf(" -\n|%d|", i);
while(curr->next != NULL)
{
printf("%d ->", curr->value);
curr = curr->next;
}
printf("NULL = %d\n -\n", list_sum(array[i]));
}
}
它不能正确打印的任何原因?如果我尝试在 create_list() 函数本身中进行任何形式的打印,它会打印这些值。
【问题讨论】:
-
我建议使用 ddd 进行调试,这样可以更深入地了解正在发生的事情。 !这个问题可能会得到负面评价。我认为您没有在 create_list 中分配足够的内存。注意 array[i] 是 *(array +i)
标签: c linked-list segmentation-fault structure pass-by-reference