读书人

结构数据的维数为什么不能取变量,该怎

发布时间: 2012-02-02 23:57:14 作者: rapoo

结构数据的维数为什么不能取变量
/*定义结构体*/
struct A{
short x;
short y;
}
下述代码怎么一编译就报错:error C2540: non-constant expression as array bound

main()
{
int m;
A* B;
B = (POSI*)malloc(sizeof(A[m]));

}


[解决办法]
B = (POSI*)malloc(sizeof(A) * M);
[解决办法]
那就不明白搂住 B = (A*)malloc(sizeof(A[m]));这一句位是么不干脆写成
B = (A*)malloc(sizeof(A[1]));呢

还有,如果只是分配 struct的空间的话,
B = (A*)malloc(sizeof(A));就可以了, 编译器会帮你计算出来你的struct A需要多大的

[解决办法]
sizeof的解析发生在编译时期,编译时必须知道它的大小才可以,所以不能在sizeof里面使用变量。

同样道理,不能定义不定大小的数组,例如:

int m = 3;
int arry[m];

[解决办法]
struct A{
short x;
short y;
};

main()
{
int m=1;
A* B;
B = (A*)malloc(sizeof(A) * m);
...................................
free(B);///////记得释放空间呀!!!!!!各位老大!!!!
return 0;
}

读书人网 >C语言

热点推荐