简体   繁体   中英

C++ cannot initialize a variable of type 'char *' with an rvalue of type 'char'

char *p = 's';

It gives out the error

cannot initialize a variable of type ' char * ' with an rvalue of type ' char '

Can anyone explain it to me? Thanks a lot.

p is a pointer, of type char* . 's' is a character literal of type char . You can't initialise a pointer from a character.

Maybe you want p to be a single character:

char p = 's';

or maybe you want it to point to a string containing the character 's' :

char const *p = "s";  // Must be const, since string literals are constant

Be thankful for your compiler. This might have worked in DOS and caused you major headaches.

You know how pointers are memory addresses? That's part of the issue. 's' can gets translated to a number in many C and/or C++ compilers. See an ASCII table

char *p = 's'; can literally sets it p memory address 0x73, or whatever the OS declares the memory address to 0x73. The compiler is going "You can't do that!"

In some forms of DOS and the right C compiler (no OS protections), you could actually do that and peek into/change whatever was stored at memory address 0x73. See http://webspace.webring.com/people/su/um_11214/vga.html for why.

You could actually mess around your video card's RAM directly in DOS just by using a pointer. This is a huge reason why in the early days of Windows, many games still came out for DOS. It was a powerful technique

you made a mistake. You should use double quotation( " ) instead of single quotation( ' ). Typically, 's' means a character literal and it is evaluated to type char .

while your p is a char type pointer( char* ) initialization doesn't work.

use "s" to get char pointer. Not that is gives you a const char * and you can type case it to a char* .

enter code here
char* p = (char*)"s";

or

const char* p = "s"

It's because 's' is indeed a char type. You'll need one of the following:

char  p = 's';
const char *p = "s";

Use the first if you really only want to manipulate a single character.

Use the second if you want a C-style string.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM