4

From this reference, In C it seems the following behavior is undefined.

int my_array[100][50];
int *p = my_array[0];
p[50]; // UB

Is there a reference in C++03 or C++11 which confirms this?

11
  • Why do you think that p[50] involves undefined behaviour? Commented Dec 8, 2011 at 9:27
  • Funny, I can compile your example with gcc -Wall -Wextra and get no warnings about any undefined behavior; change p[50] to p[50] = 1; to quiet the "no effect" warning and make sure it knows it should generate the code. (Add in some printf(3) calls if you want to make sure it doesn't optimize away the line.) Commented Dec 8, 2011 at 9:28
  • @Let_Me_Be: read the link. Seems to be asking about two different things and it needs to be clarified whether he wants to know about 2D array pointers (as per the link) or static arrays (as per his code). Commented Dec 8, 2011 at 9:28
  • 1
    @let it does not stay within the elements of the int[50] array. Commented Dec 8, 2011 at 9:44
  • 3
    It is an own entity. Subobjects are objects and objects are an entity kind (in c++). Im not aware of the notion "entity" in the context of C. Commented Dec 8, 2011 at 9:55

2 Answers 2

6

Yes in the description of the + operator. You may not dereference that pointer in C because it is a past the end pointer for the first subarray. In C++ this currently is legal because the pointer points to a valid integer (the points to relation is defined somewhere in clause 3). However in both standards adding more than 50 yields undefined behavior.

A DR was recently sent to the c++ committee about the rule that dereferencing such "valid out of thin air" pointers may be dereferenced, so i would not rely on that.

Sign up to request clarification or add additional context in comments.

2 Comments

Damn, I don't have C89 standard here, but C99 talks about a pointer that points to an array in a case of the multidimensional array, I would personally interpret this as define behaviour since the pointer doesn't point outside of the original array, only outside of the sub-array.
To clarify, when you say "Yes", you mean "Yes the behaviour is undefined"; (the question title is the negative of the question in the actual post!). And the standard section that says you can't add more than 50 is [expr.add]#5.
-1
int my_array[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
for(i=0;i<3*3;i++)
{
    printf("%d,",*(*my_array+i));
}

output is 1,2,3,4,5,6,7,8,9,

I think you can do it like that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.