Why does this:
const char cwords = "These are even more words";
result in an **error**: cannot initialize a variable of type 'const char' with an lvalue of type 'const char [22]'
but this:
const char * cwordsp = "These are more words";
Work? (Not result in an error)
It seems like the pointer cwordsp
should need to point to the memory address of that c string. Am I wrong?
A C-string is nothing more than an array of characters.
So in addition to your working example, you could also do something like this:
const char cString[] = "Hello world";
Which is basically equivalent to this:
const char cString[] = { 'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd' };
Note that this is an array of char
s, not a single char
.
The reason that you run into problems with this:
const char cString = "Hello world";
is because "Hello world";
can't possibly be interpreted as a char
. A char
type expects just a single character. Like this:
const char c = 'h';
In const char cwords = "These are even more words";
you are initializing an 8-bit integer ( const char
) with a pointer to const char
. This is an illegal conversion.
Because char is 1 byte.
You are trying to put more than 1 byte in to a datatype which holds 1 byte. const char cwords = "These are even more words";
In this example you create an array and get a pointer pointing to the first char in the array const char * cwordsp = "These are more words";
A pointer array and a regular array is almost the same thing, but only almost. You can read more about that: C/C++ int[] vs int* (pointers vs. array notation). What is the difference?
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.