用C多维数组:他们是锯齿状? [英] Multi-Dimensional Arrays in C: are they jagged?

查看:173
本文介绍了用C多维数组:他们是锯齿状?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于C编程语言的一个简单的问题(ANSI-C):

在C多维数组的锯齿状?

我的意思是 - 我们谈论的(指向其他地址在内存中的一个数组)数组的数组,或者这仅仅是长一维数组(这是按顺序存储在内存中)<? / p>

什么困扰我的是,我有点相信:

矩阵[i] [j]的等同于 *(*(矩阵+ I)+ J)


解决方案

在C A多维数组是连续的。以下内容:

  INT米[4] [5];

由4 INT [5] ■在内存布局彼此相邻。

指针数组:

 为int *米[4];

参差不齐。每个指针可以指向(第一元件)不同长度的一个单独的阵列

M [] [J] 等同于 *(*(M + 1)+ J) 。请参阅 C11标准,部分6.5.2.1:


  

下标运算符[]的德网络nition是E1 [E2]是相同的(*((E1)+(E2)))


因此​​, M [] [J] 等同于(*(M + 1))[J] ,相当于 *(*(M + 1)+ J)

这等同存在,因为在大多数情况下,阵列式衰减前pressions的指针他们的第一个元素(C11标准6.3.2.1)。 M [] [J] 是间preTED如下:


  • M 是一个数组的数组,所以它衰变的指针 M [0] ,第一子阵。

  • M + 1 是一个指向 I 次的子阵 M

  • M [] 等同于 *(M + 1),取消引用一个指针 I M 。由于这是数组类型的前pression,它衰变的指针 M [] [0]

  • M [] [J] 等同于 *(*(M + 1)+ J) ,解引用指针Ĵ日的的元素i 次的子阵 M

需要注意的是指向数组的指针从指针到他们的第一个元素不同。 M + 1 是一个指向数组的指针;它不是数组类型的前pression,并且它不衰减,是否一指针的指针或任何其他类型的

A simple question about the C programming language (ANSI-C):

Are the multi-dimensional arrays in C jagged?

I mean - are we talking about "array of arrays" (one array of pointers to other addresses in the memory) , or this is just "long one-dimensional array" (which is stored sequentially in the memory)?

What that bothers me is that I'm kinda sure that:

matrix[i][j] is equivalent to * ( * (matrix + i) + j)

解决方案

A multidimensional array in C is contiguous. The following:

int m[4][5];

consists of 4 int[5]s laid out next to each other in memory.

An array of pointers:

int *m[4];

is jagged. Each pointer can point to (the first element of) a separate array of a different length.

m[i][j] is equivalent to *(*(m+i)+j). See the C11 standard, section 6.5.2.1:

The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2)))

Thus, m[i][j] is equivalent to (*(m+i))[j], which is equivalent to *(*(m+i)+j).

This equivalence exists because in most contexts, expressions of array type decay to pointers to their first element (C11 standard, 6.3.2.1). m[i][j] is interpreted as the following:

  • m is an array of arrays, so it decays to a pointer to m[0], the first subarray.
  • m+i is a pointer to the ith subarray of m.
  • m[i] is equivalent to *(m+i), dereferencing a pointer to the ith subarray of m. Since this is an expression of array type, it decays to a pointer to m[i][0].
  • m[i][j] is equivalent to *(*(m+i)+j), dereferencing a pointer to the jth element of the ith subarray of m.

Note that pointers to arrays are different from pointers to their first element. m+i is a pointer to an array; it is not an expression of array type, and it does not decay, whether to a pointer to a pointer or to any other type.

这篇关于用C多维数组:他们是锯齿状?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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