简体   繁体   中英

Difference between two methods of array pointer initialization

Please explain the difference between

char* str = "Hello";

And

char* str = {"Hello"};

ISO 9899-1990 6.5.7 ("Initialization") says :

An array of character type may be initialized by a character string literal, optionally enclosed in braces.

There is no difference between those cases.

They both assign an address of string literal to a char pointer, but in second case an unusual syntax is used for it.

Similarly, int a = 42; and int a = {42}; are equivalent.


In the comments you've mentioned char *a = "Hello"; and char a[] = "Hello"; .

They are completely different. Second one creates an array . It means same thing as

char a[] = {'H','e','l','l','o','\0'};

There is no number inside [] becase compiler can guess array's size for you ( 6 in this case).

And another case is completely different.

When you use a "string literal" outside of intialization of char array, like in this case

printf("Hello");

or

char *a = "Hello";

compiler implictly creates an array of const char to hold your string. As you know, in these contexts name of array decays to pointer to it's first element. So,

char *a = "Hello";

and

const char internal_array[] = "Hello";

char *a = internal_array; // same as  char *a = &internal_array[0];

are equivalent .

If you try to do something like

char *a = "Hello";
a[0] = 'A';

you will get a crash, because despite being a pointer to non-const char , a actually points to a constant string. Modifying it is not a good idea.


What about other case,

char a[] = "Hello";
a[0] = 'A';

is perfectly fine. In this case you get a new array of char that holds a string. Of course it's nonconst, so you can modify it.

This one as I believe is a previously answered question. The link would be - Braces around string literal in char array declaration valid? (eg char s[] = {"Hello World"})

Both the declarations are the same. The answer to why it even existed is to provide some variety just to suit coders' tastes.(syntactic sugar) The only thing that I wanted to point out would be the char array variable declaration vs character pointer declaration. The pointers that you have defined have not been allocated any memory. Hence any edit/write operations on the string would lead to segmentation fault. Consider declaring

    char str[] = "Hello";

or

    char str[] = {"Hello"};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM