Initialize const array with pointer

Why is the first line valid and the rest invalid. I, although the former was a contraction for the latter.

const char *c = "abc"; // Why valid?

const char *b = { 'a' , 'b', 'c', '\0' }; // invalid

const int *a = { 1, 2, 3, 0 }; // invalid
+4
source share
4 answers

In the first case, you have a string literal, which is a char array, in this context it will be converted to a pointer to char.

In the following two cases, you try to use list initialization to initialize a pointer that will try to convert the first element of the list to a pointer that generates a warning, since neither char nor int pointers are pointers in the same way:

const char *b = 'a' ;

, , , , .

0

, "abc" - char[], {'a', 'b', 'c', 0} - . , :

struct s{
  char c;
  int i, j;
  float f;
} x = {'a', 'b', 'c', 0};

, const char *b = { 'a' , 'b', 'c', '\0' };, {'a'} -> 'a' . , , const char *b = { '\0' }; b NULL , .

( ), , :

const char *b = (const char[]){'a', 'b', 'c', 0};
const int *a = (const int[]){'a', 'b', 'c', 0};
struct s *x = &(struct s){'a', 'b', 'c', 0};
+3

- .

const char *c = "abc";

. Sting ( , ).

const char c[] = "abc";

( ). .

0

, C , .

: , (, int []) malloc().

:

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

then it becomes valid, because now the compiler is sure that you need an array in cumulus (temporary) memory, and it will be freed from memory after you leave the code section on which it is declared.

0
source

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


All Articles