Difference between the two array pointer initialization methods
There is no difference between these cases.
They both assign the address of a string literal to a char pointer, but the latter uses an unusual syntax.
Likewise, int a = 42;
and int a = {42};
equivalent.
In the comments you mentioned char *a = "Hello";
and char a[] = "Hello";
.
They are completely different. The second creates an array. It means that
char a[] = {'H','e','l','l','o','\0'};
There is []
no room inside . becase the compiler can guess the size of the array for you ( 6
in this case).
And another case is completely different.
When you use "string literal"
outside the intialization of the array char
like in this case
printf("Hello");
or
char *a = "Hello";
the compiler implicitly creates an array const char
to hold your string. As you know, in these contexts, the name of the array decays to a pointer to its 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 get a failure because, despite the fact that it is a pointer to const-not char
, a
in fact, points to a constant string. It's not a good idea to change it.
As for another case,
char a[] = "Hello";
a[0] = 'A';
fine. In this case, you will get a new array char
that contains the string. Of course, this is not a const, so you can change it.
source to share
This one, I believe, answered the question earlier. A reference would be - Are the parentheses around a string literal in a char array declaration valid? (eg char s [] = {"Hello World"})
Both ads are the same. The answer to why it exists at all is to provide some variety to suit the tastes of the coders (syntactic sugar) The only thing I would like to point out is the declaration of the variable w980> vs. The pointers you defined didn't get any memory. Therefore, any edit / write operations on the line will result in a segmentation fault. Consider a declaration
char str[] = "Hello";
or
char str[] = {"Hello"};
source to share