我可以将二维数组视为连续的一维数组吗? [英] May I treat a 2D array as a contiguous 1D array?

查看:38
本文介绍了我可以将二维数组视为连续的一维数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

int a[25][80];
a[0][1234] = 56;
int* p = &a[0][0];
p[1234] = 56;

第二行是否调用了未定义的行为?第四行呢?

Does the second line invoke undefined behavior? How about the fourth line?

推荐答案

这取决于解释.虽然数组的连续性要求在如何布局多维数组方面没有太多想象空间(这在之前已经指出过),但请注意,当您执行 p[1234]您正在索引仅 80 列的第零行的第 1234 个元素.有些人将唯一有效的索引解释为 0..79(&p[80] 是一个特例).

It's up to interpretation. While the contiguity requirements of arrays don't leave much to the imagination in terms of how to layout a multidimensional arrays (this has been pointed out before), notice that when you're doing p[1234] you're indexing the 1234th element of the zeroth row of only 80 columns. Some interpret the only valid indices to be 0..79 (&p[80] being a special case).

来自 C 常见问题解答的信息,这是 Usenet 在相关问题上的收集智慧C.(我认为 C 和 C++ 在这件事上没有区别,而且这非常相关.)

Information from the C FAQ which is the collected wisdom of Usenet on matters relevant to C. (I do not think C and C++ differ on that matter and that this is very much relevant.)

这篇关于我可以将二维数组视为连续的一维数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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