访问二维数组是否合法,就像一维数组? [英] Is it legal to access a bidimensional array as if it where a one-dimensional one?

查看:136
本文介绍了访问二维数组是否合法,就像一维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我可以把一个二维数组当作连续的一维数组吗?


考虑下面的代码:

  int array2d [10] [10 ]; 
int * array1d = array2d [0];

我从来没有听说过一个实现,它不会工作,但它是合法的访问和操纵 array2d via array1d ?标准的哪一部分允许这一点?标准中有什么阻止实现在每个第二级数组之间插入额外的空间或填充(而不是它的需要,但仍然)?



奖金问题:有一种方法来访问 array2d 作为 int [100] ,不需要 reinterpret_cast 还是C风格的?

解决方案

的东西是官方未定义的行为,但基本上总是工作。 [5]的左值表达式a [1] [7] )

我不是完全你得到一个数组的开始地址,并将其转换为一个指向底层类型的简单指针。]



数组需要是连续的,因此它不能在数组的元素之间插入任何填充。这是真的,无论你有一个 int 数组或数组数组。


Possible Duplicate:
May I treat a 2D array as a contiguous 1D array?

Consider the following code:

int array2d[10][10];
int *array1d = array2d[0];

I never heard of an implementation where it wouldn't work, but is it legal to access and manipulate array2d via array1d? Which section of the standard allows this? Is there anything in the standard preventing implementations from inserting extra space or padding between each of the second level arrays (not that its needed, but still)?

Bonus question: Is there a way to access array2d as an int[100] which does not require a reinterpret_cast or a C-style one?

解决方案

If memory serves, the standard gives this as an example of something that's officially undefined behavior, but essentially always works. [Edit: Here's what I was thinking of: C99, §J.2 (Undefined behavior):

  • An array subscript is out of range, even if an object is apparently accessible with the given subscript (as in the lvalue expression a[1][7] given the declaration int a[4][5])

I'm not entirely certain that applies though, as you're getting the address of the beginning of an array and converting it to a simple pointer to the underlying type.]

Arrays are required to be contiguous, so it cannot insert any padding between elements of an array. That's true whether you have an array of int or an array of arrays.

这篇关于访问二维数组是否合法,就像一维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆