Notes on c_str (char*, char [], const char*) vs. string

51 篇文章 2 订阅

Related Content:

sizeof和strlen的区别及使用详解

highlighted comments:

 

c/c++中sizeof()、strlen()、length()、size()详解和区别

==> string::length() == string::size(); the former is for c_str compatiability, latter is for STL

 

C语言 char *、char []、const char *、string的区别与相互转换

 

test code:

#include <iostream>
#include <string>
#include <typeinfo>

using namespace std;

#define DEBUG1 1
#define DEBUG0 0

int main(){
    //test string
    char cs[] = "test string";
    char* csap = cs; //usage is the same as the dynamic array but the sizeof() report 8 bytes

    //!!! but notice that char cs[] = "some string" is NOT the same as  char* csp = "some string"

   //cs[] is a mutable array of char, while char* csp points to a string constant ==> you can actually perform csp[i] = 'char' but the data csp points to won't actuallty be changed at all;


    //char* csp = "test string"; warning
    const char* csp = "test string"; //same as csap except that the string content is constant, stored in the text 
    string s = "test string";

    #if DEBUG1
    cout << sizeof(cs) << ' ' << sizeof(csap) << ' ' << sizeof(csp) << ' ' << sizeof(s) << endl; 
    //string s has actual size 32 ==> similar to vec, with reserved capacity

    cout << cs << endl << csap << endl << csp << endl << s << endl;
    cout << *cs << ' ' << *csap << ' ' << *csp << endl; //*s is not declared

    cout << ++cs[0] << ' ' << (++csap)[0] << ' ' << (++csp)[1] << ' ' << ++s[0] << endl;
    //!! ++cs is not allowed ==> char* const cs; similary ++s is not allowed either
    //++csp is fine, so is ++csap ==> they are not const*  

    cout << typeid(cs).name() << ' ' << typeid(csap).name() << ' ' << typeid(csp).name() << ' ' << typeid(s).name() << endl;

    cs[2] = 'r';
    *csap++ = 'a';
    *++csap =  'b';
    cout << cs << endl;
    //csp[2] = 'r'; // error: assignment of read-only location '*(csp + 2)' ==> global constants are stored in the .text area
    #endif

    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值