C++指针问题

一、报错“尝试读取或写入受保护的内存。这通常指示其他内存已损坏”。

出现下图问题的原因是C++中的返回类型是char*,是一个指针。而指针指向的变量被声明为局部变量,所以当函数执行完后,局部变量被销毁,指针指向了其它地方,所以会报这个错误。

另外,当把全局变量更改为局部变量进行测试时,发现程序并没有报出此错误,而在重启后才报此错误。

 

二、string类型转换为char*类型使用c_str。

1、std::string::c_str

const char* c_str const;

Get C string equivalent

Return a pointer to an array that contains a null-termianted sequence of charcters(i.e.,a C_string)representing the current value of the string object.

返回一个指向数组的指针,包括空终止字符序列(即,一个C字符串)代表的字符串对象的当前值。

This array includes the same sequence of characters that make up the value of the string object plus an additional terminating null-character('\0') at the end.

该数组包含的字符组成的字符串对象加上一个额外的空结束字符串的值相同的序列(“0”)结束时。

该数组包含相同的字符序列,这个序列由string类型的对象并且在结尾添加一个空字符串的值。

Return Value:

A pointer to the c-string representation of the string object's value.

一个c字符串指针表示string对象的值。

Example

//string  and c_string
#include <iostream>
#include <cstring>
#include <string>

int main()
{
    std::string str("Please split this sentence into tokens");
    char * cstr = new char[str.length()+1];
    
    //c_str now contains a c-string copy of str
    
    char * p = std::strtok(cstr," ");
    while(p!=0)
    {
        std::cout<<p<<'\n';
        p = std::strtok(NULL," ");
    }
    
    delete[] cstr;
    return 0;
}

2、data()

c_str()返回的指针保证指向一个size()+1长的空间,而且最后一个字符肯定"\0";

而data返回的指针则保证指向一个size()长度的空间,有没有null-terminate不保证,可能有,可能没有,要看库的实现。

 

转载于:https://www.cnblogs.com/octan/p/4346254.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值