C char array v C char * initialization

Version 6.3 is cused as valid code gcc:

char white[] = { 'a', 'b', 'c' };
char blue[]  = "abc";
char *red    = "abc";

However, the following is true:

 char *green = { 'a', 'b', 'c' };   // gcc error

I am sure that there is a reasonable reason for this, but I wonder what it is. This question is motivated by the fact that when initializing an array of bytes (so unsigned char, not char) it is very tempting to write something like { '\x43', '\xde', '\xa0' }, rather than "\x43\xde\xa0", and as soon as you forget to write my_array[]instead, *my_arrayyou get into the compiler.

+4
source share
2 answers

The following will result in an error

char *green = { 'a', 'b', 'c' };

green , . , , . , (.. white), , . , 3 .

green , , , , . 1

, :

char blue[]  = "abc";
char *red    = "abc";

blue - . , "abc". red - , "abc".


  • :

    char *green = (char[]){ 'a', 'b', 'c' };
    

    ( ), . .

+7

char white[] = { 'a', 'b', 'c' };
char blue[]  = "abc";
char *red    = "abc";

.

, , .

, , , . , .

, char *, , .

,

char unnamed = { 'a', 'b', 'c', '\0' };
char *red = unnamed;

char *green = { 'a', 'b', 'c' };   

, , .

, .

char *green = ( char[] ){ 'a', 'b', 'c' };   
+5

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


All Articles