开发者

C++ string array scope problem

开发者 https://www.devze.com 2023-02-16 06:40 出处:网络
In the below code, cout is outputting the correct string arrays.Unfortunately, in other places in the code (still in the same function and th开发者_如何学运维us not a scope error) cout << rs[i]

In the below code, cout is outputting the correct string arrays. Unfortunately, in other places in the code (still in the same function and th开发者_如何学运维us not a scope error) cout << rs[i] where 0<i<5 and i is an int, outputs a blank space. Help would be appreciated.

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";
}


The line rs[i][j] = a[i][N-1-j]; is incorrect. It is potentially writing out of bounds of the allocated string. Things seem ok when you print it right after writing there, but later on, other code will have used the space for other things. Because you're writing single characters in order to the string, you can use push_back instead.

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

This should allocate more space for the string as you need it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号