请注意以下代码段:
当我使用指针时,它一直告诉我
记住以下代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int a;
int b;
int c;
}A;
A *test;
void init(A* a)
{
a->a = 3;
a->b = 2;
a->c = 1;
}
int main()
{
test = malloc(sizeof(A));
init(test);
printf("%d\n", test->a);
return 0;
}
运行良好!现在想象一下,我想在不返回指向结构体的指针的情况下,在main
之外使用malloc
函数。我将把malloc
放在init
中,并传递test
地址。但这似乎行不通。
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int a;
int b;
int c;
}A;
A *test;
void init(A** a)
{
*a = malloc(sizeof(A));
*a->a = 3;
*a->b = 2;
*a->c = 1;
}
int main()
{
init(&test);
printf("%d\n", test->a);
return 0;
}
当我使用指针时,它一直告诉我
a
(或b
/c
)不是struct A
的成员。
struct A
。它说你试图使用的东西根本不是一个struct
。(正如下面的答案所解释的那样,你的代码被解析为*(a->a)
,a->a
相当于(*a).a
,而*a
的类型是A *
;也就是说,编译器认为你正在尝试访问指针的成员,这是毫无意义的。) - melpomeneinit
函数,在函数内部对其进行解引用和操作。 - yano