69,382
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
int num;
char name[10];
}A;
typedef struct
{
int a;
float b;
void* c;
}TEST;
int main(void)
{
TEST t = {0};
A a = {0};
(A*)t.c = (A*)malloc(sizeof(A));
t.a = 10;
t.b = 2.1f;
t.c->num = 10;
return 0;
}
t.c->num = 10;
error C2223: left of '->num' must point to struct/union
赋值是不是强制转换了吗? [quote=引用 3 楼 shao_winds 的回复:] void*表示指向一个空引用,你这么写当然不行,它根本就什么都没有指向,当然不能赋值给里面的成员
[quote=引用 楼主 Mr_warm 的回复:] 代码如下:为什么到就出错#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { int num; char name[10]; }A; typedef struct { int a; float b; void* c; }TEST; int main(void) { TEST t = {0}; A a = {0}; (A*)t.c = (A*)malloc(sizeof(A)); t.a = 10; t.b = 2.1f; t.c->num = 10; return 0; }
出错信息是:t.c->num = 10;
求原因??? 代码的意思是实现一个不定结构体,需要的时候给它指向所需的结构体。error C2223: left of '->num' must point to struct/union
(A*)t.c = (A*)malloc(sizeof(A));// 是要把结构体t中的成员c强转成A类型而已
((A*)(t.c))->num = 10;//这样直观安全
[/quote]
那就是“*”号的优先级比“.”高?赋值是不是强制转换了吗? void*表示指向一个空引用,你这么写当然不行,它根本就什么都没有指向,当然不能赋值给里面的成员
代码如下:为什么到就出错#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { int num; char name[10]; }A; typedef struct { int a; float b; void* c; }TEST; int main(void) { TEST t = {0}; A a = {0}; (A*)t.c = (A*)malloc(sizeof(A)); t.a = 10; t.b = 2.1f; t.c->num = 10; return 0; }
出错信息是:t.c->num = 10;
求原因??? 代码的意思是实现一个不定结构体,需要的时候给它指向所需的结构体。error C2223: left of '->num' must point to struct/union
(A*)t.c = (A*)malloc(sizeof(A));// 是要把结构体t中的成员c强转成A类型而已
((A*)(t.c))->num = 10;//这样直观安全
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { int num; char name[10]; }A; typedef struct { int a; float b; void* c; }TEST; int main(void) { TEST t = {0}; A a = {0}; t.c = (A*)malloc(sizeof(A)); t.a = 10; t.b = 2.1f; ((A*)(t.c))->num = 10; return 0; }
void*表示指向一个空引用,你这么写当然不行,它根本就什么都没有指向,当然不能赋值给里面的成员
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
int num;
char name[10];
}A;
typedef struct
{
int a;
float b;
void* c;
}TEST;
int main(void)
{
TEST t = {0};
A a = {0};
t.c = (A*)malloc(sizeof(A));
t.a = 10;
t.b = 2.1f;
((A*)(t.c))->num = 10;
return 0;
}