【问题标题】:Segfault when implementing a linked list with an array in C在 C 中使用数组实现链表时的段错误
【发布时间】: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


【解决方案1】:

这里有个问题:

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

参数是按值传递的,也就是说你把NULL传给create_listarraycreate_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

【讨论】:

  • 谢谢。您解决了我解决的问题,但显然还有更多问题,如下一个答案所述。
  • 我没有查看整个代码。这就是为什么我说“一个问题”而不是“问题”。通常不止一个(根据经验)。
猜你喜欢
  • 2020-09-30
  • 2021-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 2012-06-10
相关资源
最近更新 更多