简体   繁体   English

如何在C90中分配可变大小的数组?

[英]How to allocate variable size array in C90?

I need to allocate a varibale size for SYMBOLs, 我需要为SYMBOLs分配一个varibale大小,

typedef int SYMBOL

I did in following way 我按照以下方式做了

SYMBOL test[nc] , here nc is an integer. SYMBOL test[nc] ,这里nc是一个整数。 But this gives me following warning: 但这给了我以下警告:

ISO C90 forbids variable-size array

How could i do it without getting warning? 如果没有收到警告我该怎么办?

Thanks, Thetna 谢谢,Thetna

The alloca library function was intended for that before variable-sized arrays were introduced. alloca库函数用于在引入可变大小的数组之前。

It all has to do with incrementing the stack pointer. 这一切都与递增堆栈指针有关。 For the declaration of a typical constant-size array, the stack pointer is incremented with a constant that is known at compile-time. 对于典型的常量大小数组的声明,堆栈指针使用在编译时已知的常量递增。 When a variable-size array is declared, the stack pointer is incremented with a value which is known at runtime. 声明可变大小的数组时,堆栈指针会增加一个在运行时已知的值。

You would have to allocate it using malloc : 你必须使用malloc分配它:

SYMBOL* test = malloc(sizeof(SYMBOL) * nc);

// ...

free(test);

Variable length arrays are not allowed in C90, I think they were introduced in C99. C90中不允许使用可变长度数组,我认为它们是在C99中引入的。

Use malloc . 使用malloc Here you can allocate an array with the size of the input: 在这里,您可以分配一个具有输入大小的数组:

int *p;
int n;
scanf(" %d", &n);
p = malloc( n * sizeof(int) );

Also, you can access the array using ( p[0] , p[1] ,...) notation. 此外,您可以使用( p[0]p[1] ,...)表示法访问该数组。

Why not use C99? 为什么不使用C99? You can do this with gcc by adding the -std=c99 option. 您可以通过添加-std = c99选项使用gcc执行此操作。 If the compiler is smart enough to recognize that a feature is C90 vs. something else, I bet it is smart enough to handle C99 features. 如果编译器足够智能以识别某个功能是C90而不是其他东西,我敢打赌它足够智能来处理C99功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM