C / C ++:这是不确定的行为? (二维数组) [英] C/C++: Is this undefined behavior? (2D arrays)

查看:218
本文介绍了C / C ++:这是不确定的行为? (二维数组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它是未定义的行为,如果我经过一个二维数组的按以下方式?

Is it undefined behavior if I go through the elements of a 2D array in the following manner?

int v[5][5], i;

for (i = 0; i < 5*5; ++i) {
     v[i] = i;
}

话又说回来,它甚至不能编译? (我不能尝试,现在,我不在家)。如果没有,那么想象我莫名其妙地获得一个指向第一个元素,并使用诉 taht而不是[I]

推荐答案

从指针到第一个元素访问多维数组的元素是UB对于不是第一个数组中的各个元素。

Accessing elements of a multidimensional array from a pointer to the first element is UB for the elements that are not part of the first array.

由于 T阵列[N] 数组[我] 是一个直行程到UB-土地所有I> = N。即使当 T U [M] 。即使它是通过指针。这是真的有阵列上强需求(比如的sizeof(INT [N])== N * sizeof的(INT)),如其他人所说,但没有例外的是明确国产所以没有什么,可它做。

Given T array[n], array[i] is a straight trip to UB-land for all i >= n. Even when T is U[m]. Even if it's through a pointer. It's true there are strong requirements on arrays (e.g. sizeof(int[N]) == N*sizeof(int)), as mentioned by others, but no exception is explicitly made so nothing can be done about it.

因为据我可以告诉C ++标准具体的细节的C89标准,我不熟悉,无论是C89或C99标准我没有一个官方的参考。相反,我必须参考的 comp.lang.c常见问题解答

I don't have an official reference because as far as I can tell the C++ standard leaves the details to the C89 standard and I'm not familiar with either the C89 or C99 standard. Instead I have a reference to the comp.lang.c FAQ:

...]根据官方间pretation,访问的行为。(安培;阵列[0] [0])[X]还没有为定义X> = NCOLUMNS

[...] according to an official interpretation, the behavior of accessing (&array[0][0])[x] is not defined for x >= NCOLUMNS.

这篇关于C / C ++:这是不确定的行为? (二维数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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