typedef struct TestMap TestMap;
struct TestMap {
int k;
int v;
};
int main(){
TestMap *test = (TestMap*)malloc(sizeof(TestMap) * 2);
for (int i = 0; i < 2; i++) {
test[i]->k = i+1;//C2232 “->k”: 左操作数有“struct”类型,使用“.”
test[i]->v = i+2;//C2232 “->v”: 左操作数有“struct”类型,使用“.”
}
printf("test[1]->k=%d,test[1]->v=%d\n", test[1]->k, test[1]->v);//报错C2232
//释放test内存
return 0;
}
我很困惑为什么不能用->访问,然后看了这篇博文解答了一些疑惑。就好比动态分配数组中元素的类型是int不是int*。为了正确使用"->"和".",我写了如下代码:
typedef struct TestMap TestMap;
struct TestMap {
int k;
int v;
};
int main(){
TestMap *test = (TestMap*)malloc(sizeof(TestMap) * 2);
for (int i = 0; i < 2; i++) {
test[i].k = i+1;
test[i].v = i+2;
}
printf("test[1].k=%d,test[1].v=%d\n", test[1].k, test[1].v);
TestMap *test2 = (TestMap*)malloc(sizeof(TestMap));
test2->k = 2;
test2->v = 2;
printf("test2->k=%d,test2->v=%d\n", test2->k, test2->v);
//释放test内存
//释放test2内存
return 0;
}
运行结果:
如果想在TestMap数组中使用->访问,那就应该创建TestMap指针数组,就像这样
typedef struct TestMap TestMap;
struct TestMap {
int k;
int v;
};
int main(){
TestMap **test3 = (TestMap**)malloc(sizeof(TestMap) * 2);
for (int i = 0; i < 2; i++) {
test3[i] = (TestMap*)malloc(sizeof(TestMap));
test3[i]->k = i + 1;
test3[i]->v = i + 2;
}
printf("test3[1]->k=%d,test3[1]->v=%d\n", test3[1]->k, test3[1]->v);
//释放test3内存
return 0;
}