简体   繁体   中英

Character Pointer and string variable

I tried to use a character Pointer go throw string character (iterate) but I found i can not say the below:

string Name = "Hello";
char *ch = Name;

like the previous statements i am getting error during execution.

However when I am doing like that:

char *ch = "Hello";

the program running without throwing any exception.

Why is that?

I have recently encountered similar problem and the simplest answer is that std::string is a different type from char* , more precisely std::string is an object which contains some characters (your text) and few methods, which allow you to do multiple operations with your text. You can imagine creating a class Integer for storing the value, but also a method allowing you to square and cube the number which is stored in the Ingerer class. Even though they could store the same numerical value, you will not be able to compare them (unless you overload the operator== ), as their types are different.

If you wish to use the code you provided, you need to rewrite the second line as

const char *ch = Name.c_str();

it is allowed because std::string contains a method c_str() which "casts" itself to const char* . If you want to learn more about strings, be sure to visit C++ reference about strings .

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