cv_gordon

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::

string 是一个类,其中有一个 char * 类型的私有变量。 因此可以如下构建一个string类型的变量。

string str = "abcd";

其中,右值“abcd”一个字符串,存储在常量区的连续内存中,以 '\0' 作为结束标志位,返回一个指向该段内存起始位置的 char * 指针。通过重载赋值运算符 = ,可以使用 char * 类型变量给str赋值。

 

https://blog.csdn.net/u012611878/article/details/78291036

 

 

    char a[] = "ABC";  // return char *, in stack
    char b[] = {'A', 'B', 'C', ' '};  // return char *, in stack
    
    const char* c[] = {"A","B"}; // return (const char *)*, for example int v[10] = {1},return int *
    
    const char *d = "ABC";
    
    cout << "In constant area :" << (void*)"ABC" << endl;
    cout << "In stack area :" << (void*)a << endl;
    cout << a << endl;
    cout << a[0] << endl;
    cout << sizeof(a)/sizeof(char) << endl;
    cout << "********************" << endl;
    
    cout << "In stack area :" << (void*)b << endl;
    cout << b << endl;
    cout << b[0] << endl;
    cout << sizeof(b)/sizeof(char) << endl;
    cout << "********************" << endl;

    cout << c << endl;//void*
    cout << c[0] << endl;
    cout << sizeof(c)/sizeof(c[0]) << endl;
    cout << "********************" << endl;
    
    cout << "In constant area :" << (void*)d << endl;
    cout << d << endl;
    cout << *d << endl;
    cout << d[0] << endl;
    cout << sizeof(d)/sizeof(d[0]) << endl;

 

 

输出char指针地址

由于C++重载输出运算符 << ,把 char * 类型的变量当做字符串变量。于是当遇到 char * 类型的变量时,输出指针指向的内容。如果想输出 char * 变量的地址,必须使用强制类型转换,把字符指针转换为无类型指针。

const char * m_data = "abcd";
cout << static_cast<const void *>(m_data) << endl;

 

posted on 2019-09-20 10:11  cv_gordon  阅读(1213)  评论(0编辑  收藏  举报