My main blog: half an acre of Square pond
The following content is original, reproduced please be sure to indicate the address
Main reference information: I raised the question in StackOverflow why the first was right and the second is wrong?
This tangled two lines of code such as the following:
const char *cval = "nothing"; correct int *ival = {1, 2, 3, 4}; Error
Why is the first line of code correct the second line of code error? Since "Nothing" is stored as an array in memory, why is it possible to define a cval pointing to it instead of defining an array with ival pointing to the following? This is really a very tangled problem, look at the following analysis:
First, let's look at the first line of code:
const char *cval = "nothing";
The assignment operator on the right side is astring literal Constants, the compiler stores string literal constants in a contiguous set of address cells in the memory space, andthe type of storage is const char[], the form of storage is:{‘n‘, ‘o‘, ‘t‘, ‘h‘, ‘i‘, ‘n‘, ‘g‘, ‘\0‘}
, it is very important that the const char[] type is converted to the const char* when assigning the string literal in the right side of the assignment operator to the left side of the operand, because the array name itself is a pointer, so the conversion is reasonable and legitimate, so this part of the code is correct;
Take a look at this part of the code below:
How is this part of the code wrong? This is because the compiler does not agree to store {1, 2, 3, 4} in memory separately, but must copy it to the corresponding contiguous address cell of an object, obviously, to the right of the assignment operator is just a pointer type to int, not a condition to store {1, 2, 3, 4}, so this part of the code is wrong 。
because in the C language, since C99, there is a feature called Compund literal, so for the 2nd line of code, in C we can make for example the following changes to make it correct:
int *ival = (int []) {1, 2, 3, 4};
The above line of code in C + + is not tenable, there are errors generated, think about why? This is because C and C + + language features are not the same, in C, the assignment operator in the code above the right side is a persistent value, is a constant object, it is created with a persistent address, but in C + +, the right side operand is just a temporary object, does not have a persistent address,
(int []) {1, 2, 3, 4}
at the end of this expression the address has died, and I personally think that this is the C and C + + languagesRight Valuethe differences in the normative, for this reason welcome to provide different references.
Two lines of code that are tangled