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.
int size means that size is a variable and C does not allow variable size arrays.
But, unlike the normal arrays, variable sized arrays cannot be initialized.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With