Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 625
Haoran Jia Avatar asked Mar 26 '15 02:03

Haoran Jia


Video Answer


2 Answers

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
like image 187
Mike Seymour Avatar answered Nov 15 '22 00:11

Mike Seymour


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"
like image 28
ANjaNA Avatar answered Nov 14 '22 22:11

ANjaNA