为什么该C链表程序给予

为什么该C链表程序给予

本文介绍了为什么该C链表程序给予'分段错误“?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一个函数读取有一堆的'字符的,并把他们在一个链接列表中的文件。它不工作:(

The first function reads a file that has a bunch of 'char's and puts them in a linked list. It is not working :(.

#include <stdio.h>
#include <stdlib.h>

struct list {
    char val;
    struct list* next;
};

typedef struct list element;

int lcreate(char* fname, element* list);
int ldelete(element* list);
int linsert(char a, char b, element* list);
int lremove(char a, element* list);
int lsave(char* fname, element* list);



int lcreate(char* fname, element* list) {
    element* elem = list;
    char c = 0;
    FILE * file = NULL;

    file = fopen(fname, "r");

    while ((c = getc(file)) != EOF)
    {
        if(list == NULL) {
            list = (element*)malloc(sizeof(element));
            if(list == NULL) {
                return 0;
            }
            list->val = c;
        }
        else {

            elem->next=(element*)malloc(sizeof(element));
            elem = elem->next;
            elem-> val = c;
        }
    }
    fclose(file);
    elem->next = NULL;
    return 1;
}



int main(void) {
    int i = 0;


    element * list = NULL;
    lcreate("list.txt", list);

    for(i = 0; i<4; ++i) {
        printf("%c", list->val);
        list = list->next;
    }

    return 0;
}

固定的问题'文件'被空。

Fixed problem with 'file' being null.

推荐答案

一个明显的问题就在这里:。

One obvious problem is right here:

FILE * file = NULL;

fopen(fname, "r");

对于的fopen 来大有作为,需要指定由的fopen 的结果到你的 FILE *

For the fopen to accomplish much, you need to assign the result from fopen to your FILE *:

file = fopen(fname, "r");

编辑:既然你用C的工作,你无法通过引用传递指针。作为一种替代方法,可以将指针传递给一个指针:

Since you're working in C, you can't pass the pointer by reference. As an alternative, you can pass a pointer to a pointer:

int lcreate(char *fname, element **list) {

     // ...
     *list = malloc(sizeof(element));
     (*list)->next = null;
     (*list)->val = c;
// ...
}

基本上,所有的 lcreate 里面的code将需要参考 *名单,而不是仅仅列表。另外,你可以用一个指针指向现有列表作为输入,并在你必须像一个指针返回列表,因此:列表= lcreate(LIST.TXT清单);

Basically, all the code inside of lcreate will need to refer to *list instead of just list. Alternatively, you can take a pointer to an existing list as input, and return a pointer to the list, so in main you'd have something like: list = lcreate("list.txt", list);

这篇关于为什么该C链表程序给予'分段错误“?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 08:16