[C] Declare array of variable size

Discussion in 'Mixed Languages' started by Stannieman, Jan 19, 2012.

  1. Stannieman

    Stannieman MDL Guru

    Sep 4, 2009
    2,232
    1,818
    90
    Hi,
    I'd like to ask the user for a value, and then declare an array with that size.
    Like "char arrayName[value];"

    This doesn't seem to be possible however, as all declarations must happen before any other statements in the function or method.

    Is there any way go get around this? Of course I can create a very large array to be safe, but that's not efficient.
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  2. tigo

    tigo MDL Novice

    Dec 8, 2011
    8
    1
    0
    #2 tigo, Jan 19, 2012
    Last edited by a moderator: Apr 20, 2017
    you can use malloc like this

    Code:
    char *arrayname = (char *)malloc(value);
    arrayname[0] = 'M';
    OR in c++

    Code:
    char *arrayname = new char[value]
    
     
  3. Stannieman

    Stannieman MDL Guru

    Sep 4, 2009
    2,232
    1,818
    90
    #3 Stannieman, Jan 19, 2012
    Last edited by a moderator: Apr 20, 2017
    (OP)
    I can't use cpp (school says so), but the fist on does the job, thanks!
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...