使用2维数组作为1维数组正确吗?可能导致不确定的行为? [英] Is using 2 dimensional array as 1 dimensional array correct? May cause Undefined Behaviour or so?

查看:75
本文介绍了使用2维数组作为1维数组正确吗?可能导致不确定的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码正确吗?

char tab1[3][3];

for(int i = 0; i < 3; i++)
    for(int j = 0; j < 3; j++)
       tab1[i][j] = (char)i;

printf("%c", ((char*)tab1)[3]); // == tab1[1][0]


推荐答案

如果没有其他原因,这很好,因为 char 可以根据标准对所有其他类型进行别名。另外,多维数组被分配为连续块,因此它是内存中的一维数组。

This is fine, if for no other reason, because char can alias all other types according to the standard. Also multidimensional arrays are allocated as a contiguous block so it is a one dimensional array in memory to begin with.

我们知道 tab1 会衰减到指向连续多维数组(即数组)的第一个元素的指针,并将该 array 指针转换为 char * (可以使用任何别名)必须没问题。

We know that tab1 decays to a pointer to the first element of a contiguous multidimensional array (which is an array) and casting that array pointer to a char* (which can alias anything) must be fine.

如果有疑问,您可以随时执行& tab1 [0] [0] 。再次因为我们知道分配的内存是连续的。

If in doubt you could always do &tab1[0][0]. Again because we know the allocated memory is contiguous.

编辑

如果这是一个整数数组( int tab1 [3] [3] ),那么情况就有些不同了。据我了解,之前 C ++ 17 该标准说,指向正确对象类型的指针有效 它如何获得其价值。这意味着强制转换为 int * 应该很好,因为我们知道 tab1 产生的地址与的地址相同。第一个元素。

If this was an integer array (int tab1[3][3]) then the story is a little different. To my understanding before C++17 the standard says that a pointer to the correct object type is valid regardless of how it obtained its value. That means casting to int* should be fine because we know the address yielded by tab1 is the same as the address of the first element.

但是之后 C ++ 17 保证已被删除因此此强制转换可能是未定义的行为

However after C++17 that guarantee has been removed so this cast is likely undefined behavior.

有关详细信息,请参阅此问题

由于这个原因,我会总是建议使用& tab1 [0] [0] ,它会总是有效。

For that reason I would always recommend using &tab1[0][0] which will always be valid.

这篇关于使用2维数组作为1维数组正确吗?可能导致不确定的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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