除非先前已分配(并释放),否则不能引用指向函数的结构指针

can't reference a struct pointer to function unless it has been previously allocated (and freed)

我应该写一个很长的代码解释,但解释已经在下面的代码中所以我想我的问题是:我如何让它工作而不用 malloc 然后释放它?或者基本上在这种情况下正确的写法是什么?

#include <stdio.h>
#include <malloc.h>

struct d {
    int f;
};

struct d* rr() {
    struct d* p = malloc(sizeof (struct d*));
    p->f = 33;
    return p;
}

void rr2(struct d* p) {
    p = malloc(sizeof (struct d*));
    p->f = 22;
}



int main()
{
    //works..
    struct d* g;
    g = malloc(sizeof (struct d));
    g->f = 45;
    printf("[%i]", g->f);
    
    //works..
    g = rr();
    printf("[%i]", g->f);
    

    //below, both are same, except in this first case, g is allocated then freed..
 
    //works..
    free(g);
    rr2(g);
    printf("[%i]", g->f);
    
    //doesn't work..
    struct d *q;
    rr2(q);
    printf("[%i]", q->f);



    return 0;
}

两个功能的初学者

struct d* rr() {
    struct d* p = malloc(sizeof (struct d*));
    p->f = 33;
    return p;
}

void rr2(struct d* p) {
    p = malloc(sizeof (struct d*));
    p->f = 22;
}

有错字。看来你的意思是

    struct d* p = malloc(sizeof (struct d));
                                 ^^^^^^^^

    p = malloc(sizeof (struct d));
                       ^^^^^^^^^

    struct d* p = malloc(sizeof ( *p ));
                                 ^^^^^

    p = malloc(sizeof ( *p) );
                       ^^^^^

至于这个功能

void rr2(struct d* p) {
    p = malloc(sizeof (struct d*));
    p->f = 22;
}

那么在这次通话中

struct d *q;
rr2(q);

指针q按值传递给函数。所以函数处理指针的副本q。在函数内更改副本不会反映在原始指针上 q。它保持不变。

要使代码正常工作,您必须通过引用传递指针(间接通过指向它的指针)。在这种情况下,函数看起来像

void rr2(struct d **p) {
    *p = malloc(sizeof (struct d ));
    ( *p )->f = 22;
}

并被称为

rr2( &q );

至于这段代码

free(g);
rr2(g);
printf("[%i]", g->f);

那么它只是调用未定义的行为,因为在这个语句中

printf("[%i]", g->f);

可以访问已释放的内存。