为什么要打印Hp而不是空行?

时间:2019-04-08 12:04:17

标签: c++

我有一个非常简单的问题,为什么这段代码的输出是这样?

我正在将Dev-C ++ 5.11与TDM-GCC 4.9.2 64位一起使用

#include <iostream>
using namespace std;
int main()
{
    char *ptr;
    char Str[] = "abcdefg";
    ptr = Str;
    ptr += 8;
    cout << ptr;
    return 0;
}

我希望代码会显示一个空行。

由于某种原因,位置7似乎有一个空格字符,您可以通过将ptr +=8;更改为ptr+=7;来检测到。

但是对我来说更奇怪的是,除非您跳出数组限制2个,否则将无法显示3个字符,在这种情况下,我们将指针加8。字符是:“ H,(一个怪异的正方形),p”

screenshot of the output from my computer

2 个答案:

答案 0 :(得分:4)

  

我希望代码会显示一个空行。

这种期望被误导了。该程序的行为是不确定的。

  

由于某种原因,位置7似乎有一个空格字符。

没有。位置7处有一个空终止符。

  

但是对我来说更奇怪的是,除非您超出数组限制2个字符,否则将无法显示另外3个字符。

访问数组超出其边界的行为是不确定的。

答案 1 :(得分:0)

You cannot expect the empty line when you try to access memory beyond your array. At position 7 you have the '\0'.
C strings are terminated by this character and it is also used by the printing function to know when it should stop printing.

At position 8 you are beyond this character and the behavior of the program is undefined since the memory you are accessing might be everything.
The characters that you are able to print are just a representation of the memory beyond the string. They might change or exception might be thrown.

Character 'a' is at position 0 and character 'g' is at position 6 you should not access memory outside of this region except if you are trying to hack something.