gpt4 book ai didi

c - C中两个数组元素地址之间的偏移量

转载 作者:太空宇宙 更新时间:2023-11-04 01:49:05 26 4
gpt4 key购买 nike

我有一个问题要求我找到两个数组元素地址之间的字节偏移量:

double myArray[5][7];

If C stored data in column-major order the offset (in bytes) of &myArray[3][2] from &myArray[0][0] would be:

在列的主要顺序中,我认为元素应该这样布局:

[0][0] -- [1][0] -- [2][0] -- [3][0] -- ..... -- [3][2]

所以在我看来,以字节为单位获取偏移量是计算 [0][0] 和 [3][2] 之间的跳跃次数,然后乘以 8,因为它是一个 double 组。但是,令我感到困惑的是它要求使用 & 运算符进行偏移。这会以某种方式改变答案,因为它在两个地址之间询问,还是过程仍然相同?我认为它会是一样的,但我不是 100% 确定。

如果我的想法是正确的,那么这会是 8*15 字节吗?

最佳答案

二维数组的内存布局将是一 block 连续的内存。(根据您的问题)

int x[2][3] = {{0,1,2},{3,4,5}};

这将在(您的问题)中列出

--+--+--+--+--+--+
0| 3| 1| 4|2 |5 |
--+--+--+--+--+--+

但在 C 中,它的存储方式类似于

--+--+--+--+--+--+
0| 1| 2| 3|4 |5 |
--+--+--+--+--+--+

现在你完全正确了,你可以考虑在 [0][0][3][2] 之间跳转,但还有更好的方法无需考虑所有这些,您可以确定它们的偏移量将是它们的地址差异。

您可以简单地获取他们的地址并减去它们。

ptrdiff_t ans = &a[3][2]-&a[0][0];(这基本上就是两个元素之间的差距)

这产生了答案。 printf("answer = %td",ans*sizeof(a[0][0]);(一个间隙 = sizeof(a[0][0]) ) [在你的情况下 double]

或者更好的方法是

ptrdiff_t ans = (char*)&a[3][2] - (char*)&a[0][0];//number of bytes between them.

我将解释一下为什么 char* 在这里很重要:

(char*)&a[0][0]&a[0][0] 都包含相同的东西 value-wise . (这还不够通用)

但它在指针运算中很重要。 (解释不同)。

不使用强制转换时,解释为数组元素的数据类型。这意味着现在它考虑了 double 的区别。当您转换它时,它会在 char-s 中吐出结果或差异。

为什么这有效?因为所有数据存储器都是byte 可寻址的,而char 是单字节的。


这比想象中的要多,首先让我们看看C中的数组是什么?

C 并没有真正的多维数组。在 C 中,它被实现为数组的数组。是的,这些多维数组元素以行优先顺序存储。

为了更清楚一点,我们可以查看标准 §6.5.2.1

的示例

考虑声明定义的数组对象

      int x[3][5];

Here x is a 3 x 5 array of ints; more precisely, x is an array of three element objects, each of which is an array of five ints. In the expression x[i], which is equivalent to (*((x)+(i))), x is first converted to a pointer to the initial array of five ints. Then i is adjusted according to the type of x, which conceptually entails multiplying i by the size of the object to which the pointer points, namely an array of five int objects. The results are added and indirection is applied to yield an array of five ints. When used in the expression x[i][j], that array is in turn converted to a pointer to the first of the ints, so x[i][j] yields an int.

所以我们可以说 double myArray[5][7]; 这里 myArray[3][2]myArray[0][0] 不属于同一数组。

现在我们已经完成了 - 让我们进入其他内容:

来自标准§6.5.6.9

When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements.

但是这里 myArray[3]myArray[0] 表示两个不同的数组。这意味着 myArrayp[3][2]myArray[0][0] 都属于不同的数组。他们不是最后一个元素。 因此标准不会定义减法 &myArray[3][2] - &myArray[0][0] 的行为。

埃里克(Eric Postpischil)指出了这个想法。

关于c - C中两个数组元素地址之间的偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47425674/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com