簡體   English   中英

在C中使用數組實現鏈表時出現段錯誤

[英]Segfault when implementing a linked list with an array in C

好吧,首先,我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
    }
}

一個問題在這里:

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

參數按值傳遞,這意味着您將NULL傳遞給create_list ,並且當create_list返回時, array仍將為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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM