多维数组出界访问 [英] Multidimensional array out of bound access

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

问题描述

我目前正在学习如何在c中操纵多维数组

我有以下代码

  int t [2] [2] = {{12,14},{16,18}};int * p = t [0];printf(%d \ n",*(p + 2)); 

然后打印 16 .

但是我的问题是,我正在访问仅包含两个int元素的第一个数组的第三个元素,这种访问的行为未定义吗?

我知道用于访问一维数组的绑定索引的行为是不确定的.例如

  int ar [] = {11,22};printf(%d \ n",ar [2]);//行为未定义 

但是对于多维数组也是如此吗?

解决方案

C将多维数组存储为连续的内存区域.但是,尽管我之前在第一行中所说的仍然可以解释您所做的事情,但这仍然是未定义的行为.

看起来很奇怪,但是您可以阅读以进行更多检查.

问题在 C 中,二维数组的概念是通过使用数组数组来实现的,其中数组的每个元素都是一个数组.

这样想,

p 是指向第一个数组的衰减指针.当您访问 p [2] 时,尽管您可能会获得相关的输出,但这仍然是未定义的行为.


t 是一个数组,每个元素都是一个数组( t [0],t [1] ).

现在, t [0] 是一个数组,当分配给 p 时,该数组将衰减并指向第一个元素.现在,您访问未定义行为的 p [2] ,因为您正在访问其有效索引为 0 1 的数组.


您可能觉得很奇怪-在 C 中,正常工作并不总是意味着它是按标准定义和备份的.出于相同的考虑,这似乎是合乎逻辑的事情,但这并不是定义最明确的方法.

I'm currently learning how to manipulate multidimensional array in c

I have the following code

int t[2][2] = {
        {12, 14},
        {16, 18}
};

int * p = t[0];

printf("%d\n", *(p + 2));

And 16 is printed.

But my question is, I'm accessing the third element of the first array that only contained two int elements, is the behaviour for this kind of access undefined?

I understand the behaviour for accessing out of bound index for a single dimensional array is undefined. e.g.

int ar[] = {11, 22};
printf("%d\n", ar[2]); //behaviour undefined

But is it also true for multidimensional array?

解决方案

C stores a multi-dimensional array as a contiguous memory area. But still what you have done though is explained by what I said earlier in first line , it's still Undefined Behavior.

Strange it may seems but you can read this to check more.

The thing is in C the concept of 2d array is realized by using array of arrays where each element of the array is an array.

So think this way,

p is the decayed pointer to the first array. When you access p[2] though you may get relevant output it is still Undefined behavior.


t is an array each element of which is an array (t[0],t[1]).

Now t[0] is an array which when assigned to p is decayed and points to the first element. Now you access p[2] that is Undefined behavior because you are accessing an array for which valid indices are 0 and 1.


It may seem strange to you - that in C things working doesn't always mean it's defined and backed up by standard. Here on the same note it might seem logical thing to do but it isn't the most defined way to do things.

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

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