Difference between string and char * And const_cast & lt; & gt ;()

Source: Internet
Author: User

First, string is a class, and char * is a basic data type.

Second, const_cast can only change the const attribute of the pointer, but cannot change or remove its own const attribute.

Test code:

 

 

// MemcpyTest. cpp: defines the entry point of the console application. // # Include "stdafx. h "# include" string "using namespace std; int _ tmain (int argc, _ TCHAR * argv []) {string Str =" abcd "; char * pChar = "mmnddd"; // pChar [0] = 'J'; // access conflict exception // char * pstr1 = Str. c_str (); // type exception // const char * pstr1 = Str. c_str (); pstr1 [0] = 'G'; // error char * pStr = const_cast <char *> (Str. c_str (); // remove the const attribute pStr [0] = 'H'; char * pchar1 = const_cast <char *> (pChar ); // remove the const attribute // pchar1 [0] = 'E'; // an access conflict exception occurs, the const attribute cannot be removed. // if you want to remove the const attribute, the heap space must be allocated. char * pchar2 = new char [8]; // pchar2 = pChar; // pchar2 [0] = 'E'; // This does not work either, but the Pointer Points to the same memory area. No one in this area can change memcpy (pchar2, pChar, sizeof (pchar2) * 2); pchar2 [strlen (pChar) + 1] = '\ 0'; pchar2 [0] = 'E'; // return 0 correctly;

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.