allocate an array

Discussion in 'C Programming' started by Simon, Jul 3, 2003.

  1. Simon

    Simon Guest

    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.
     
    Simon, Jul 3, 2003
    #1
    1. Advertisements

  2. Simon

    Marc Boyer Guest

    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
     
    Marc Boyer, Jul 3, 2003
    #2
    1. Advertisements

  3. Simon

    Chris Dollin Guest

    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>.
     
    Chris Dollin, Jul 3, 2003
    #3
  4. Simon

    Simon Guest

    thanks a lot.

    i got it

     
    Simon, Jul 3, 2003
    #4
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.