Initializing String and Array in C - Difference

I experimented with ways to initialize arrays and strings in C and found that:

char *str = "ABCDE"; 

perfectly initializes the string without errors or warnings, but:

 int *array = {1,2,3,4,5}; 

gives me warnings and, in the end, unloads the kernel. It really bothers me, and I would like to know why this ad works for characters, but not for integers ...

EDIT: I am using the gcc compiler.

+4
source share
2 answers

It will work for ints by doing this:

 int array[] = {1,2,3,4,5}; 

or that:

 int *array = (int[]){1,2,3,4,5}; 

"string" tells the compiler all the information it needs (size, type) to create an instance of the string (or an array of bytes with the NULL terminator). Naked {} does not, unless you declare it as a composite literal . Adding ints[] tells the compiler that the initiated data is an array of integers.

As Nathan noted in the comments, there are subtle differences from the two statements.

First, defines an array of 5 ints on the stack. This array can be modified and live to the end of the function.

The second one, 1) defines an anonymous array of five ints on the stack 2) defines a pointer "array" for the first element of the anonymous array on the stack. The pointer should not be returned since the memory is on the stack. Furthermore, an array is not essentially const like a string literal.

EDIT: Replace the cast compound literal as indicated by the commenter.

+7
source

The string literal splits into a const pointer to char. While this is an array {1,2,3,4,5} in C and does not decay. Therefore, you will have to use the syntax to create arrays in C, for example:

 int a[] = {1,2,3,4,5} ; 

Then you can point it out:

 int a[] = {1,2,3,4,5} ; int *p = a; 

Since the name of the array is the address of the array or the first element. Hope this helps.

+4
source

Source: https://habr.com/ru/post/1435686/


All Articles