开发者

Array of pointers can be accessed beyond last element C++ [duplicate]

This question already has answers here: Why is the phrase: "undefined behavior means the compiler can do anything it wants" true? (2 answers) Accessing an array out of bounds gives no error, why? 开发者_高级运维 (18 answers) Array index out of bound behavior (10 answers) Undefined, unspecified and implementation-defined behavior (9 answers) How dangerous is it to access an array out of bounds? (11 answers) Closed 9 hours ago.

I am trying to create a 3*N array where N is specified at runtime.

 int *array[3];
 int breadth;
 cin>>breadth;

    for(int i=0;i<3;i++)
        array[i] = new int[breadth];

    array[0][breadth-1] = 1;
    array[1][breadth-1] = 2;
    array[2][breadth-1] = 3;
    array[3][breadth-1] = 69; // how does this work

    cout<<array[3][breadth-1]<<endl;

The output is 69 and I am surprised that the indicated line works even though the maximum size (3) has been exceeded. Does anyone know why that element is accessible?

I tried other sizes like 4N and 5N, with the same results

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜