What is the difference between c_str () and data () of string?

Source: Internet
Author: User

The local Windows system has vs2008 environment installed. Check the source code of the xstring file and find the c_str () and data () implementation of the xstring class as follows:

const _Elem *__CLR_OR_THIS_CALL c_str() const{// return pointer to null-terminated nonmutable arrayreturn (_Myptr());}const _Elem *__CLR_OR_THIS_CALL data() const{// return pointer to nonmutable arrayreturn (c_str());}

Is there a difference ???

A test code is written as follows:

#include<stdio.h>#include<cstring>#include<string>using std::string;int _tmain(int argc, _TCHAR* argv[]){sTopic = "hello world";const char* pC_str = sTopic.c_str();printf("sTopic.c_str()=%d, sizeof(...)=%d, strlen(...)=%d\n", pC_str, sizeof(sTopic.c_str()), strlen(pC_str) );const char* pData = sTopic.data();printf("sTopic.data()=%d, sizeof(...)=%d, strlen(...)=%d\n", pData, sizeof(sTopic.data()), strlen(pData) );char * pTemp = const_cast<char*>(sTopic.c_str() );pTemp[0] = 'a'; printf("modify [0]='a' after const_cast(sTopic.c_str() ) sTopic=%s\n", sTopic.c_str() );pTemp = const_cast<char*>(sTopic.data() );pTemp[1] = 'b';printf("modify [1]='b' after const_cast(sTopic.data() ) sTopic=%s\n", sTopic.c_str() );return 0;}

The result is:

Stopic. c_str () = 23859240, sizeof (...) = 4, strlen (...) = 11
Stopic. Data () = 23859240, sizeof (...) = 4, strlen (...) = 11
Modify [0] = 'A' after const_cast (stopic. c_str () stopic = aello world
Modify [1] = 'B' after const_cast (stopic. Data () stopic = abllo world

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.