美文网首页
C++ 的string越界问题

C++ 的string越界问题

作者: professordeng | 来源:发表于2018-11-05 21:56 被阅读0次

在 C++ 中 string 是一个类,里面包含一个 char 类型数组,可以利用 append() 或者 += 重载符扩展数组。

如果直接用下标访问,则可以会出现越界。如下

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

string test(string s1) {
    string s;
    for(int i = 0; i < 100; i++)
        s[i] = '0';
    return s;
}

int main() {
    string s;
    s += test(s);
    s += "fsdgsgas";
    cout << s << endl;
    cout << s.size() << endl;
    getchar();
    return 0;
}

正确的做法是用 += 重载符在 string 后面添加内容。

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

string test(string s1) {
    string s;
    for(int i = 0; i < 100; i++)
        s += '0';
    return s;
}

int main() {
    string s;
    s += test(s);
    s += "fsdgsgas";
    cout << s << endl;
    cout << s.size() << endl;
    getchar();
    return 0;
}

相关文章

网友评论

      本文标题:C++ 的string越界问题

      本文链接:https://www.haomeiwen.com/subject/cdmexqtx.html