简体   繁体   中英

Output from char array

Can someone explain why I get this odd output?

Why it doesn't output only one arr[b] every time?

123.in

2
QWERT
YUIOP
ASDFG
HJKLZ
XCVBN
QWERT
YUIOP
ASDFG
HJKLZ
XCVBN


Main.cpp

int main() {
int n;
char arr[5][5];
    ifstream source;
    source.open("123.in");

source >> n;
for(int i=0; i<=n; i++) {
    for(int r=0; r<5; r++){
            source >> arr[r];
            cout << arr[r] << endl;
    }
    for(int b=0; b<5; b++)
        cout << " WHY: " << arr[b]<< endl;
}
source.close();
    return 0;
}


Output

QWERT
YUIOP
ASDFG
HJKLZ
XCVBN
 WHY: QWERTYUIOPASDFGHJKLZXCVBN
 WHY: YUIOPASDFGHJKLZXCVBN
 WHY: ASDFGHJKLZXCVBN
 WHY: HJKLZXCVBN
 WHY: XCVBN

Why cout << arr[r] << endl; and cout << " WHY: " << arr[b]<< endl; doesn't output the same code?

Your data is stored like this:

arr:

[0][0]  [0][1] [0][2]  [0][3]  [0][4]  [1][0]  [1][2]  [1][3]  [1][4]  [2][0]  [2][1]  [2][2]  [2][3]  [2][4]  [3][0]  [3][1]  [3][2]  [3][3]  [3][4]  [4][0]  [4][1]  [4][2]  [4][3]  [4][4]  [][]

Q     | W     | E     | R     | T     | Y     | U     | I     | O     | P     | A     | S     | D     | F     | G     | H     | J     | K     | L     | Z     | X     | C     | V     | B     | N    

When you say that you want to

cout << arr[3];

that means start displaying my content at "arr[3][0]" and continue till you hit the NULL character. "arr[number]" is really a pointer to another array. Because all of the arrays were initiallized at the same time (char arr[5][5];) it puts the arrays back to back in memory.

For instance, if you do this:

cout << arr[0][7] << endl;

you will get "I" as the output, because it counts 7 up from the "arr" pointer, which starts at [0][0], which happens to land on "I"

~ Edit per request:

Please note that when you are working with pointers (which an array in c++ really is) that it is easy to disregard the '\\0' character that terminates the array. In your example you get lucky that the next character is NULL, but this is not always the case. The string could have continued displaying random characters stored in memory until it happened upon a NULL character. Best practice involves keeping track of the size of the arrays to ensure unintentional results cannot occur.

C++ expects your C-strings (char arrays) to end in a special "end-of-line" symbol (you can escape it as '\\0'). Since you filled each 5-letter string to the brim, it doesn't know when to stop reading. For example, "QWERT" would be represented as 6 characters instead of 5:

'Q', 'W', 'E', 'R', 'T', '\\0'

When cout starts reading it doesn't find that last character, so it keeps reading the following memory positions. In this case, the next row: "YUIOP". And so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM