I'v read in a book that when you have a string like this "blabla"
, it means there is a hidden char array, and this expression returns the address to the first element, and it's like a const array .
This makes me confused about 2 scenarios :
char a[7] = "blabla"
, is not possible because the "blabla" returns an address to the first element of an array, so how would you put an address into a
instead of actual elements ?
it says when you see "blabla" it means like a const
char array , and that means I can't change a
, at all (which is not true).
I guess something really basic here is unclear to me.
According to the C Standard (6.3.2.1 Lvalues, arrays, and function designators)
3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.
So in this declaration
char a[7] = "blabla";
the elements of the string literal that has the type of character array char[7]
due to including the terminating zero as an element of the string literal are used to initialize the elements of the character array a
In fact this declaration is equivalent to the declaration
char a[7] = { 'b', 'l', 'a', 'b', 'l', 'a', '\0' };
Take into account that in C string literals have types of non-constant character arrays. Nevertheless they themselves may not be modifiable.
From the C Standard (6.4.5 String literals)
7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
So you may write for example
char *s = "blabla";
In this case according to the first quote from the C standard the string literal is converted to pointer to its first element and the value of the pointer is assigned to the variable s
.
That is in the static memory there is created an unnamed character array and the address of the first element of the array is assigned to the pointer s
. You may not use the pointer to change the literal that is you may not write for example
char *s = "blabla";
s[0] = 'B';
In C++ string literals indeed have types of constant character arrays. So you have to write in a C++ program
const char *s = "blabla";
In C you may also to write
char a[6] = "blabla";
^^^^
In this case the terminating zero of the string literal will not be used to initialize the character array a
. So the array will not contain a string.
In C++ such a declaration is invalid.