Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I not getting a compile error when declaring a C array with variable size?

Tags:

arrays

c

My understand has always been that when I declare an array on the stack with a size that comes in as a variable or parameter, I should get an error.

However, I noticed that I do not get any error if I do not explicitly initialize the array (yes, it won't be on the stack, but I'm wondering about the lack of error). For example, the following code does not compile because of array2:

#define N 30

void defineArrays(int n)
{
    int i,j;
    int array1[N] = {};

    int array2[n] = {};

    for(i=0; i<N; ++i) array1[i] = 0;

    for(j=0; j<n; ++j) array2[j] = 0;
}

But the following code compiles and runs, even when I send a real n from main:

#define N 30

void defineArrays(int n)
{
    int i,j;
    int array1[N] = {};

    int array2[n];

    for(i=0; i<N; ++i) array1[i] = 0;

    for(j=0; j<n; ++j) array2[j] = 0;
}

What I am missing here? Is it declaring array2 as a pointer? I'm using gcc

Update: Thanks for everyone who answered. The problem was indeed that my version of gcc was defaulting to C99 for some strange reason (or not so strange, maybe I'm just too old), and I incorrectly assumed that it defaults to C90 unless I tell it otherwise.

like image 253
Uri Avatar asked Mar 30 '09 19:03

Uri


People also ask

Can you declare an array with a variable size in C?

int size means that size is a variable and C does not allow variable size arrays.

Can you initialize array with variable size?

But, unlike the normal arrays, variable sized arrays cannot be initialized.


2 Answers

C99 introduced the ability to have variable length arrays which is now available in GCC (although it's reported as not being totally standards compliant). In the second example, you appear to be taking advantage of that functionality.

Link to GCC's info about variable length arrays: http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html

like image 154
JaredPar Avatar answered Oct 20 '22 18:10

JaredPar


I think that you need to choose you C standard version.

gcc -fsyntax-only -std=c89 -pedantic -x c -

<stdin>: In function ‘defineArrays’:
<stdin>:6: warning: ISO C forbids empty initializer braces
<stdin>:8: warning: ISO C90 forbids variable length array ‘array2’

vs.

gcc -fsyntax-only -std=c99 -pedantic -x c -
<stdin>: In function ‘defineArrays’:
<stdin>:6: warning: ISO C forbids empty initializer braces
like image 41
CB Bailey Avatar answered Oct 20 '22 19:10

CB Bailey