使用C中的数组实现链接列表时的Segfault

时间:2014-03-27 08:15:10

标签: c arrays linked-list

好吧,首先,我100%肯定不是我的打印功能搞乱了这个程序,但是我的输出是打印“pre”然后是segfaulting。我相信它发生在我的create_list函数中。我在该函数中的逻辑是数组(链表listdef是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 个答案:

答案 0 :(得分:1)

这里有一个问题:

Node** array = NULL; 
int length = create_list(array, fp);

参数按值传递,这意味着您将NULL传递给create_listarray返回时create_list仍为NULL。

有几种方法可以解决这个问题。例如:

Node** array = NULL; 
int length = create_list(&array, fp);

int create_list(Node*** arrayp, FILE* fp){ 
    int length, i, index, value;
    Node **array;

    fscanf(fp, "%d\n", &length); 

    array = *arrayp = malloc(sizeof(Node*)*length); //allocate memory for the pointers