Does C99 guarantee that arrays are contiguous?

前端 未结 3 1759
春和景丽
春和景丽 2020-11-29 06:01

Following an hot comment thread in another question, I came to debate of what is and what is not defined in C99 standard about C arrays.

Basically when I define a 2D

3条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 06:33

    I've added some more comments to our original discussion.

    sizeof semantics imply that int a[5][5] is contiguous, but visiting all 25 integers via incrementing a pointer like int *p = *a is undefined behaviour: pointer arithmetics is only defined as long as all pointers invoved lie within (or one element past the last element of) the same array, as eg &a[2][1] and &a[3][1] do not (see C99 section 6.5.6).

    In principle, you can work around this by casting &a - which has type int (*)[5][5] - to int (*)[25]. This is legal according to 6.3.2.3 §7, as it doesn't violate any alignment requirements. The problem is that accessing the integers through this new pointer is illegal as it violates the aliasing rules in 6.5 §7. You can work around this by using a union for type punning (see footnote 82 in TC3):

    int *p = ((union { int multi[5][5]; int flat[25]; } *)&a)->flat;
    

    This is, as far as I can tell, standards compliant C99.

提交回复
热议问题