Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing string and array in C - The difference

Tags:

c

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.

like image 372
Maputo Avatar asked Dec 20 '22 16:12

Maputo


2 Answers

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.

like image 81
James Avatar answered Dec 24 '22 02:12

James


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.

like image 43
Lews Therin Avatar answered Dec 24 '22 01:12

Lews Therin