gpt4 book ai didi

C++字符串数组作用域问题

转载 作者:行者123 更新时间:2023-11-28 08:22:32 25 4
gpt4 key购买 nike

在下面的代码中,cout正在输出正确的字符串数组。不幸的是,在代码的其他地方(仍然在同一个函数中,因此不是范围错误)cout << rs[i]其中 0<i<5i是一个 int , 输出一个空格。帮助将不胜感激。

int N;
inp >> N;
string a[N]; //For matchee
string b[N]; //For matcher
string rs[N]; //For reflection
for(int i=0; i<N; i++) {
inp >> a[i];
}
for(int i=0; i<N; i++) {
inp >> b[i];
}
/*Build the reflection matrix*/
bool reflectCorrect = 1;
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) {
rs[i][j] = a[i][N-1-j];
cout << rs[i][j];
if(!(rs[i][j] == b[i][j])) {
reflectCorrect=0;
}
}
cout << "\n";
}

最佳答案

rs[i][j] = a[i][N-1-j]; 行不正确。它可能会超出分配的字符串的范围。当您在此处写入后立即打印它时,事情似乎没问题,但稍后,其他代码将使用该空间做其他事情。因为您要按照字符串的顺序写入单个字符,所以您可以改用 push_back。

rs[i].push_back(a[i][N-1-j]);

这应该根据需要为字符串分配更多空间。

关于C++字符串数组作用域问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5287011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com