访问多维数组的元素是否超出了未定义的行为范围? [英] Is accessing an element of a multidimensional array out of bounds undefined behavior?

查看:58
本文介绍了访问多维数组的元素是否超出了未定义的行为范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请原谅令人困惑的问题标题,但是我不确定如何用更清楚的措词来表达疑问.

Pardon the confusing question title, but I was unsure how to phrase it more clearly.

在C语言中,超出范围访问数组的行为归为未定义行为.但是,保证数组元素在内存中连续放置,并且数组下标运算符是指针算术的语法糖(例如 x [3] == *(x + 3)).因此,我个人希望以下代码的行为得到明确定义:

In C, accessing an array out of bounds is classified as undefined behavior. However, array elements are guaranteed to be laid out contiguously in memory, and the array subscript operator is syntactic sugar for pointer arithmetic (e.g x[3] == *(x + 3)). Therefore, I would personally expect the behavior of the code below to be well-defined:

int array[10][10];
int i = array[0][15]; // i == array[1][5]?

如果我对标准的解释是正确的,那么这将是未定义的行为.我错了吗?

If my interpretation of the standard is correct, this would be undefined behavior. Am I wrong?

推荐答案

根据标准,这显然是未定义的行为,因为这种情况在

According to the standard, it is clearly undefined behaviour as such a case is explicitly listed in the section J.2 undefined behaviour (found in an online C99 standard draft):

即使对象显然是数组下标,也超出范围可使用给定的下标访问(如左值表达式中所示)给出声明 int a [4] [5] )(6.5.6)的 a [1] [7] .

您的示例仍然可以工作,实际上我已经在C代码中看到了很多这样的情况;但是,准确地说是UB.

It can still be the case that your example will work, and actually I have seen a lot of such cases in C code; However, to be accurate, it is UB.

这篇关于访问多维数组的元素是否超出了未定义的行为范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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