开发者

How to allocate variable size array in C90?

I need to allocate a varibale size for SYMBOLs,

typedef int SYMBOL

I did in following way

SYMBOL test[nc], here nc is an integer. But开发者_StackOverflow中文版 this gives me following warning:

ISO C90 forbids variable-size array

How could i do it without getting warning?

Thanks, Thetna


The alloca library function was intended for that before variable-sized arrays were introduced.

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:

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

// ...

free(test);

Variable length arrays are not allowed in C90, I think they were introduced in C99.


Use 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.


Why not use C99? You can do this with gcc by adding the -std=c99 option. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜