I was experimenting with ways to initialize arrays and strings in C, and found that:
char *str = "ABCDE";
perfectly initializes the string with no errors or warnings, but:
int *array = {1,2,3,4,5};
gives me warnings and eventually dumps core. It really bugs me now and I would like to know why this sort of declaration works for characters but doesn’t for integers…
EDIT: I’m using the gcccompiler.
It will work for ints by doing this:
or this:
"string"tells the compiler all the information it needs (size,type) to instantiate the string (aka an array of bytes with a NULL terminator). A naked{}does not unless you declare it as a compound literal. Adding theints[]tells the compiler that the initiated data is an array of ints.As Nathan pointed out in the comments there are subtle differences to the two statements.
The first, defines an array of 5 ints on the stack. This array can be modified and lives until the end of the function.
The second, 1) defines an anonymous array of five ints on the stack 2) defines a pointer ‘array’ to the first element of the anonymous array on the stack. The pointer should not be returned since the memory is on the stack. Also the array is not inherently const like a string literal.
EDIT: Replaced cast with compound literal as pointed out by commentator.