指针数组问题

use*_*955 0 c++

int test[3] = {1,2,3};
cout<<test[3]<<endl;    
// this will get a error
Run Code Online (Sandbox Code Playgroud)

但

int test[3] = {1,2,3};
int (*A)[3];
A = &test;
cout<<test[3]<<(*A)[3]<<endl;  
// this will print -858993460 withiout any errors
Run Code Online (Sandbox Code Playgroud)

所以有人能告诉我为什么吗?我真的很困惑.

在第一种情况下,为什么它不是outboundbound错误,而是一个未定义的错误?为什么第二种情况不会出错?我以前认为他们是一样的......

实际上我确实知道数组从0开始,我很困惑为什么第一个得到错误但第二个不会????

Oli*_*rth 10

您正在调用未定义的行为.在这两种情况下,您的索引都超出了数组的范围; 相应的行为未定义.它可能会崩溃,或者可能会输出废话,或者它可能会做其他事情.

  • +1.所以简而言之:**永远不要再这样做了!**:) (2认同)