Unexpected results when printing array and char to screen with cout

后端 未结 2 1790
灰色年华
灰色年华 2021-01-17 02:09

As a beginner of learning C++, I am trying to understand the difference between an array of type char and an array of type int. Here is my code:

2条回答
  •  青春惊慌失措
    2021-01-17 02:56

    Okay let's go over each separately.

    Print int array: 0xbfd66a88
    

    Here you print an int[] which goes into the operator << overload that takes int*. And when you print a pointer you see a memory address in hexadecimal format.

    Print int array[0]: 5
    

    Here you print the first element of the array which is an int. As expected.

    Print int array[0]+1: 6
    

    Here you add 1 to the first element of the array and print the result, which is still an int. 5+1 becomes 6. No mystery here.

    Print char array: abcd
    

    This is a bit trickier. You print a char[] and there is a special overload for operator << that takes a const char* and that one gets called. What this overload does is print each character beginning from the address where the pointer points until it finds a terminating zero.

    Print char array[0]: a
    

    Here you print a char so the overload that takes char gets called. It prints the corresponding ASCII character, which is 'a'.

    Print char array[0]+1: 98
    

    Here the result of operator+ is an int because the literal 1 is an int and the char value gets promoted to the wider type (int). The result is 98 because the ASCII code of the letter 'a' is 97. When you print this int you just see the number.

提交回复
热议问题