Pointer-to-array overlapping end of array

前端 未结 6 860
花落未央
花落未央 2020-12-31 00:43

Is this code correct?

int arr[2];

int (*ptr)[2] = (int (*)[2]) &arr[1];

ptr[0][0] = 0;

Obviously ptr[0][1] would be inva

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-31 01:15

    Not an answer but a comment that I can't seem to word well without being a wall of text:

    Given arrays are guaranteed to store their contents contiguously so that they can be 'iterated over' using a pointer. If I can take a pointer to the begin of an array and successively increment that pointer until I have accessed every element of the array then surely that makes a statement that the array can be accessed as a series of whatever type it is composed of.

    Surely the combination of: 1) Array[x] stores its first element at address 'array' 2) Successive increments of the a pointer to it are sufficient to access the next item 3) Array[x-1] obeys the same rules

    Then it should be legal to at least look at the address 'array' as if it were type array[x-1] instead of type array[x].

    Furthermore given the points about being contiguous and how pointers to elements in the array have to behave, surely it must be legal to then group any contiguous subset of array[x] as array[y] where y < x and it's upper bound does not exceed the extent of array[x].

    Not being a language-lawyer this is just me spouting some rubbish. I am very interested in the outcome of this discussion though.

    EDIT:

    On further consideration of the original code, it seems to me that arrays are themselves very much a special case in many regards. They decay to a pointer, and I believe can be aliased as per what I just said earlier in this post.

    So without any standardese to back up my humble opinion, an array can't really be invalid or 'undefined' as a whole if it doesn't really get treated as a whole uniformly.

    What does get treated uniformly are the individual elements. So I think it only makes sense to talk about whether accessing a specific element is valid or defined.

提交回复
热议问题