The following is accepted as valid c
code by gcc
version 6.3:
char white[] = { 'a', 'b', 'c' };
char blue[] = "abc";
char *red = "abc";
However the following fails:
char *green = { 'a', 'b', 'c' }; // gcc error
I am sure there is a perfectly rational reason for this to be the case, but I am wondering what it is. This question is motivated by the case when having to initialize an array of bytes (so unsigned char
rather than 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 of *my_array
, you get caught by the compiler.
char arr[] = {'c','o','d','e','\0'}; In the above declaration/initialization, we have initialized array with a series of character followed by a '\0' (null) byte. The null byte is required as a terminating byte when string is read as a whole.
You can initialize a one-dimensional character array by specifying: A brace-enclosed comma-separated list of constants, each of which can be contained in a character. A string constant (braces surrounding the constant are optional)
For the array, the total string is stored in the stack section, but for the pointer, the pointer variable is stored into stack section, and content is stored at code section. And the most important difference is that, we cannot edit the pointer type string.
char* means a pointer to a character. In C strings are an array of characters terminated by the null character.
The following will produce an error
char *green = { 'a', 'b', 'c' };
Because the initializer for green
isn't an array of characters as you believe. It doesn't have a type, it's just a brace-enclosed initializer list. The thing that it initializes in the previous samples (i.e. white
) determines how it's interpreted. The same initialzier can be used to initialize any aggregate that is capable of holding 3 characters.
But green
is a pointer, and not an aggregate, so you can't use a brace-enclosed initializer list as it's initial value.1
Now, the following two work but with very different semantics:
char blue[] = "abc";
char *red = "abc";
blue
is an array. It will hold the same contents as the literal "abc"
. red
is a pointer that points at the literal "abc"
.
You can use a compound literal expression:
char *green = (char[]){ 'a', 'b', 'c' };
It tells the compiler to create an unnamed object (the life time of which depends on the scope of the declaration), that is of character array type and is initialized with those three characters. The pointer is then assigned the address of that object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With