【发布时间】:2014-03-27 08:15:10
【问题描述】:
好的,首先,我 100% 肯定,不是我的打印功能搞砸了这个程序,而是我的输出是打印“pre”,然后是段错误。我相信它发生在我的 create_list 函数中。我在那个函数中的逻辑是数组(链表 typedef 是 Node,所以 head 是 Node*,包含头的数组是 Node**)包含几个不同链表的头,并根据存储每个分支到索引(输入中的第一个数字)。但显然我的编程逻辑并不等于我的想法。任何帮助都会很棒,谢谢。
int main(int argc, char *argv[]){
if ( argc != 2 ) {
printf("Insufficient arguments.\n");
return 0;
}
FILE* fp = fopen(argv[1], "r");
printf("here");
while(fp == NULL){
char file[MAX_FILE_LENGTH];
printf("Unable to open file, enter a new file name: ");
scanf("%s", file);
fp = fopen(file, "r");
}
Node** array = NULL;
int length = create_list(array, fp);
fclose(fp);
printf("pre\n");
print_list(array, length);
return 0;
}
int create_list(Node** array, FILE* fp){
int length, i, index, value;
fscanf(fp, "%d\n", &length);
array = malloc(sizeof(Node*)*length); //allocate memory for the pointers
for(i = 0; i < length; i++){
array[i] = NULL; //set all the pointers to null
}
while ( !feof(fp) ) //until it reaches eof
{
fscanf(fp, "%d %d\n", &index, &value);
Node* node = new_node(value); //get the node
if ( array[index] == NULL ) { //if nothing is in there yet at the index
array[index] = node; //make whatever is at the index this node
}
else { //otherwise
Node* head = array[index]; //head equals the thing
while ( head->next != NULL ) { //go through the list until next is null
head = head->next;
}
head->next = node; //then make that null next point to the new node
}
}
return length;
}
void print_list(Node** array, int length){
int i;
for(i = 0; i < length; i++){
Node* curr = array[i]; //make the head what's stored in the array
printf(" %d ", i); //index
printf("%d ->", curr->value); //print the value
curr = curr->next; //move it
}
}
【问题讨论】:
-
1.您的 create 函数不会按地址传递数组基指针。要么将新数组基址作为函数结果返回,要么传递基址指针地址。 2. 这个:
while ( !feof(fp) )is wrong..
标签: c arrays linked-list