C.正确处理指向函数的双指针,该函数会分配一个结构并返回指向它的指针-可以在不同的函数中读取,显示,释放

时间:2018-08-20 20:19:01

标签: c pointers malloc structure

当我在“ main”函数中动态分配内存时,程序运行正常。现在,我想分配“读取”功能,但是每次尝试都失败了。

我认为我的问题出在我的“主”函数中:我不知道如何从函数“读取”中检索结构(指针),然后由函数“ destroy”释放它的动态分配内存。

int main(void)
{
    int err_code;
    struct student_t** s=(struct student_t**)malloc(1024*sizeof(struct student_t*));
    **s = &read(err_code); //here is: error: lvalue required as unary '&' operand.
    //But I think that my problem is wider than just this error.

    if (s==NULL) {
        puts("Error\n");
    }

    display(s);
    destroy(s);

    return err_code;
}


我想做的是:创建一个struct类型的指针,指向该结构的指针,由“ read”函数返回。然后将此**指针传递给“ destroy”函数,以释放已分配的内存。

功能。
用户在功能“读取”中插入分配给结构的数据。返回指向动态分配的结构的指针,如果有任何错误,则返回NULL。

struct student_t* read(int *err_code)
{   printf("Insert data:\n");
    struct student_t* p = (struct student_t *)malloc(1024*sizeof(struct student_t));
    *err_code=1;
    if (p==NULL) {
        puts("Error\n");
        return NULL;
    }
//then it's supposed to read from user and assing to struct. Code below in links.
}


struct student_t {
    char name[20];
    char surname[40];
    int index;
};


功能释放动态分配的内存,除非“读取”失败并返回NULL。

void destroy(struct student_t **s)
{
if (s!=NULL) free(s);
}


我的显示功能。但是,我认为我的问题开始得较早。

void display(const struct student_t **s) //here I'm unsure if it should be *s- or **s-function.
{
    if(s!=NULL) printf("%s %s, %i\n", (*s)->name, (*s)->surname, (*s)->index);
}

我的“阅读”功能基于我先前问题的答案。当我在“ main”中正确分配内存时,它可以工作。我使用的“读取”代码为:How to detect if user inserts data with commas (in a desired format) or not? 我无法正确处理所有我想正确处理的其他错误:How to scanf commas, but with commas not assigned to a structure? C

我真的很感谢所有帮助,一切就像我150小时的救赎  为一项任务而奋斗。

1 个答案:

答案 0 :(得分:1)

您有两个错误:

  1. 您问的是因为您做错了所有事情。函数返回的值是所谓的 r-value 。之所以这样命名,是因为它只能位于作业的右侧。比这复杂一点,但是对r值或 l值(可以指定为 left -手的东西)的常规测试是是否可以使用地址运算符&获取其地址。 R值不能带有地址。

    (简单的)解决方案很简单:

    *s = read(err_code);
    
  2. 第二个错误是因为,当您传递普通的read变量时,int需要一个指向int的指针作为其参数。在这里,您应该使用地址运算符:

    *s = read(&err_code);
    

还有其他一些问题,最大的问题是需要s作为指向指针的指针。难道不能只是一个单指针,然后简单地做

    struct student_t *s = read(&err_code);

另一个问题是,在许多系统中可能已经存在一个read函数(最著名的是POSIX系统,例如Linux和macOS),因此该函数的声明会相互冲突。