allocate an array

S

Simon

Hello everybody,

I've got a problem. I'm trying to allocate an array inside a function with
Parameter int n:
main(){
int i;
....
i = strlen(ch);
array(i);
....
}


int array ( int n ){
int a[n];
....
}
but when i compile:

error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2133: 'a' : unknown size
error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0


how can i do now?
Thank u in advance for your afforts.
 
M

Marc Boyer

Simon said:
Hello everybody,
int array ( int n ){
int a[n];
...
}
but when i compile:

error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2133: 'a' : unknown size
error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0

Perhaps because your compiler does not accept C99 ?
To my knowledge, this construction is in C99, but not
in C89.
Change your compiler, or use "malloc".

Marc Boyer
 
C

Chris Dollin

Simon said:
I've got a problem. I'm trying to allocate an array inside a function with
Parameter int n:
main(){
int i;
...
i = strlen(ch);
array(i);
...
}


int array ( int n ){
int a[n];
...
}

You can't do that in (pre-99) C. Instead of allocating an array,
allocate some heap space (and remember to free it), eg:

int *a = malloc( n * sizeof (*a) );

Remember to #include <stdlib.h>.
 
S

Simon

thanks a lot.

i got it

Chris Dollin said:
Simon said:
I've got a problem. I'm trying to allocate an array inside a function with
Parameter int n:
main(){
int i;
...
i = strlen(ch);
array(i);
...
}


int array ( int n ){
int a[n];
...
}

You can't do that in (pre-99) C. Instead of allocating an array,
allocate some heap space (and remember to free it), eg:

int *a = malloc( n * sizeof (*a) );

Remember to #include <stdlib.h>.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top