Confusion over character array initialization

What's the difference between

   char ch [ ] = "hello";

and

   char ch [ ] = { 'h','e','l','l','o','\0'};

and why we can only do

   char *p = "hello";

But can not do

   char *p = {'h','e','l','l','o','\0'};
+3
source share
5 answers

Two array declarations are the same. As for the pointer declaration, the form is char *p = {'h','e','l','l','o','\0'};not valid, simply because it was not included in the compiler project.

According to my information, there is no theoretical reason why this announcement should not be valid when char *p = "hello";.

+2
source
char ch [ ] = "hello";
char ch [ ] = { 'h','e','l','l','o','\0'};

There is no difference. The object chin both ads will be exactly the same.

Why can't we do:

char *p = {'h','e','l','l','o','\0'};

( ). char * .

:

char ch [ ] = "hello";

char *p = "hello";

. , - .

+3

, const

"" const char * const, char *. , .

. . .

char [] = { 'a', 'b', ...};,

char *p = "hello". , const char *p = "hello", .

, . . char *p = {'h','e','l','l','o','\0'}; .

. , , .

+1

. : char ch "hello".

char ch[] = "hello";

ch . .

char ch[] = {'h', 'e', 'l', 'l', 'o', '\0'};  

char p, , "hello". . , C , C++, undefined .

char *p = "hello";
const char *p = "hello";  // better

.

char *p = {'h','e','l','l','o','\0'};

p char , . array pointer , , . , , . , . sizeof.

+1

char ch [ ] = "hello";
char ch [ ] = { 'h','e','l','l','o','\0'};

char *p = "hello";  //This is correct

char *p = {'h','e','l','l','o','\0'};  //This is wrong

,

char *p[]={'h','e','l','l','o','\0'}; //This works
-2

All Articles