c数组:动态设置大小? [英] c arrays: setting size dynamically?

查看:224
本文介绍了c数组:动态设置大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C编程新手.我正在尝试使用变量设置数组的大小,但出现错误:数组"的存储大小不是恒定的

I am new to C programming. I am trying to set the size of the array using a variable but I am getting an error: Storage size of 'array' isn't constant !!

01 int bound = bound*4;

02 static GLubyte vertsArray[bound];

我注意到,当我用数字"20"替换 bounds (在第02行的括号内)时,程序可以正常运行.但是我试图动态设置数组的大小...

I have noticed that when I replace bounds (within the brackets on line 02) with the number say '20', the program would run with no problems. But I am trying to set the size of the array dynamically ...

我为什么会收到此错误的任何想法? 非常感谢,

Any ideas why I am getting this error ? thanks much,

推荐答案

您会收到此错误,因为正如编译器告诉您的那样,您的数组大小不是恒定的.在C语言的C89/90版本中,数组大小必须为常数.您不能动态设置数组的大小".如果需要运行时大小的数组,则必须使用malloc手动分配它,或使用某些非标准的编译器特定方法(例如alloca函数).

You are getting this error because, as the compiler told you, your array size is not constant. In C89/90 version of C language array size has to be a constant. You can't "set the size of the array dynamically". If you need a run-time sized array, you have to either allocate it manually with malloc or use some non-standard compiler-specific approach (like alloca function).

在C语言的C99版本中,添加了对所谓的可变长度数组(VLA)的支持. C99编译器将接受自动数组的运行时大小的数组声明.但是,即使在C99中,您也无法像尝试那样声明运行时大小的 static 数组.

In C99 version of C language support for so called Variable-Length Arrays (VLA) was added. A C99 compiler would accept run-time sized array declaration for an automatic array. Yet even in C99 you can't declare a static array of run-time size, as you are trying to.

这篇关于c数组:动态设置大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆