在C语言中使用数组实现链表时出现段错误



好吧,首先,我100%肯定这不是我的打印函数搞砸了这个程序,但是我的输出是打印"pre"然后分割。我相信它发生在我的create_list函数中。我在该函数中的逻辑是,数组(链表类型为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("pren");
    print_list(array, length);
    return 0;
    }
int create_list(Node** array, FILE* fp){ 
    int length, i, index, value;
    fscanf(fp, "%dn", &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 %dn", &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, "%dn", &length); 
    array = *arrayp = malloc(sizeof(Node*)*length); //allocate memory for the pointers

相关内容

  • 没有找到相关文章

最新更新