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 gcc
compiler.
It will work for ints by doing this:
int array[] = {1,2,3,4,5};
or this:
int *array = (int[]){1,2,3,4,5};
"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 the ints[]
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.
The string literal decays to a const pointer to a char. Whereas this is an array {1,2,3,4,5} in C and does not decay. So you will have to use the syntax for creating arrays in C, like so:
int a[] = {1,2,3,4,5} ;
Then you can point to it:
int a[] = {1,2,3,4,5} ;
int *p = a;
Because the name of an array is the address of the array or the first element. Hope that helps.
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