This code compiles and produce output like I would expect.
#include <stdio.h>
int* ar[];
int main(void) {
ar[0] = 97;
ar[1] = 98;
ar[2] = 99;
printf("%i\n", ar[0]);
printf("%i\n", ar[1]);
printf("%i\n", ar[2]);
printf("%i\n", ar[3]);
return 0;
}
/* output
97
98
99
0
*/
I have a feeling that I’m doing this wrong on so many levels. Are there any ill effects here, what are they?
Moreover, why does the array of pointers work as global variable, while if I declare it in main, gcc raises an error?
At least couple problems:
1)
aris an array of pointers – you’re assigning ints to it (and printing the elements as ints). I get warnings about this from both GCC and MSVC.2) the declaration of
aris an ‘incomplete type’ since it doesn’t have the size specified. MSVC refuses to link saying that it can’t resolve thearsymbol, which is what I’d expect. GCC does link, providing a warning:I prefer the MSVC behavior in this case.
In GCC’s case, you’re accessing data for 3 or 4 array elements with only 1 element actually existing, so you’re accessing memory that doesn’t properly belong to an object, which is undefined behavior. It’ll result in memory corruption, a crash, or apparently working – even though the program isn’t correct (as in your test).