简体   繁体   中英

why it cannot convert char* to char

In c++ we can write
1 char *s="hello"

but the below lines of program produces an error ( cannot convert char* to char)
2 char *s; *s="hello"; char *s; *s="hello";

I am confused here, what is difference between 1 and 2 why this error is coming?

In C++, a string literal is a constant array of characters, not just an array of characters like in C. Anyways, to assign to such a variable (Which is best avoided), you do not have to dereference the pointer. Dereferencing it accesses the first element, which is just a char. A char cannot hold an array of characters inside it, causing an error. This is more the reason why you should be using std::string .

Some compilers such as GCC provide extensions to make such code possible since it is not standards compliant code, and it would look like:

char* s = "hello";
s = "new string";

This generates the following warning in GCC (But still gets the expected result):

warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

Clang also has the same behavior with the same output (Also generating a warning)

A string is an array of characters. The start of a string therefore is const char * . Therefore to reference a string, you can use const char * s = "hello";

However if you dereference a const char* , you get a const char . This isn't a string ie *s gives you 'h'.

In your code *s="hello"; , you are saying "assign at the dereferened s the value "hello"". Dereferencing s is a character only, to which you are trying to assign a string.

The problem is the second asterisk in your second example.

The first code is this

char *s="hello";

The equivalent code is this

char *s; 
s="hello";

No * before s in the second line.

Now as everyone is pointing out neither of these are legal C++. The correct code is

const char *s="hello";

or

const char *s; 
s="hello";

Because string literals are constant, and so you need a pointer to const char .

I am confused here, what is difference between 1 and 2 why this error is coming?

As many others * in C++ means different things in different context:

char *s; // * here means that s type is a pointer to char, not just char
*s;      // in this context * means dereference s, result of exression is char
int a = 5 * 2; // in this context * means multiply

so case 1 and 2 may look similar to you but they mean very different things hence the error.

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