【C语言报错】C2232——内存分配与“.“和“->“的关系

 

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;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值