简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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