Re: [std-discussion] Pointers into mutlidimensional arrays

1,309 views
Skip to first unread message

Tadeus Prastowo

unread,
Apr 8, 2019, 8:00:47 AM4/8/19
to std-discussion
On Mon, Apr 8, 2019 at 12:45 PM <ndkr...@gmail.com> wrote:
> Consider the following program:
>
> #include <iostream>
>
> int a[2][2] = {{1, 2}, {3, 4}};
>
> int main() {
>
> int* p0 = &a[0][0] + 3; // line 7
> std::cout << *p0 << std::endl; // line 8
>
> unsigned char* p2 = reinterpret_cast<unsigned char*>(&a) + 3 * sizeof(int); // line 10
> std::cout << +*p2 << std::endl; // line 11
> int* p3 = reinterpret_cast<int*>(p2); // line 12
> std::cout << *p3 << std::endl; // line 13
>
> int* p1 = reinterpret_cast<int*>(&a) + 3; // line 15
> std::cout << *p1 << std::endl; // line 16
>
> }
>
> Which lines cause undefined or implementation-defined behavior? I'm most interested in C++17 and later drafts, but information about earlier versions and C are also welcome (as the C++ rules are based on C, but with some changes).
>
> Here are my best guesses (references to draft N4810):
>
> Line 7: Pointer addition is undefined behavior according to 7.6.6¶4.3.

I think it is not undefined because p0 points to the hypothetical
element a[0][3], satisfying the inequality 0 <= i + j <= n. See also
[basic.compound]p3.

> Line 8: (Irrelevant as depends on line 7.)

This might be undefined, but I cannot quickly find the relevant
passage in N4810.

> --
>
> Nick

--
Best regards,
Tadeus
Reply all
Reply to author
Forward
Message has been deleted
Message has been deleted
Message has been deleted
Message has been deleted
0 new messages