是否保证子阵列线性分配? [英] Are Sub-Arrays Guaranteed to be Allocated Linearly?

查看:92
本文介绍了是否保证子阵列线性分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道此答案违反了

I know this answer is in violation of the reinterpret_cast rules but it also presumes that sub-arrays will be allocated linearly.

我相信这并不能保证,但是当我搜索标准时,我发现自己的信心开始动摇.如果我静态分配2D数组,像这样:

I believed this was not guaranteed, but as I search the standard, I find my confidence wavering. If I statically allocate a 2D array, like this:

int foo[][4] = { { 5, 7, 8 },
                 { 6, 6 },
                 {},
                 { 5, 6, 8, 9 } };

我可以假设所有元素都是线性分配的吗?也就是说,如果foo[0]位于地址0x00000042,将:

Am I allowed to assume that all elements will be allocated linearly? That is to say that if foo[0] is at address 0x00000042, will:

  • foo[1]的地址为0x00000052
  • foo[2]的地址为0x00000062
  • foo[3]的地址为0x00000072
  • foo[1] be at address 0x00000052
  • foo[2] be at address 0x00000062
  • foo[3] be at address 0x00000072

这些地址以十六进制表示,是的,它们为具有sizeof(int) == 4的4元素子数组提供空间;它们可能会也可能不会被零初始化.

These addresses are in hex, and yes they are providing space for the 4-element sub-array with sizeof(int) == 4; they may and may not be zero-initialized.

推荐答案

是否可以保证线性分配子阵列?

Are Sub-Arrays Guaranteed to be Allocated Linearly?

是的.无论数组的元素是子数组还是非数组对象,都可以保证它们连续存储在内存中.

Yes. Whether the elements of the array are sub-arrays or non-array objects, they are guaranteed to be stored contiguously in memory.

为完整起见,这是标准报价:

For completeness, here is the standard quote:

[dcl.array]

[dcl.array]

  1. [snip]数组类型的对象包含一个连续分配的非空的N个类型为T的N个子对象.[snip]
  1. [snip] An object of array type contains a contiguously allocated non-empty set of N subobjects of type T. [snip]

T是数组的情况也不例外.

There is no exception for the case when T is an array.

因此,我们知道不能保证const char[4]会是这种情况.

相反,我们确实知道对象可以保证 ,就像其他类型可以保证一样.

On the contrary, we do know that this is guaranteed for char[4] objects just like it is guaranteed for other types.

例如:const char first [] ="foo"; char foo [] [4] = {"bar"","foo",","baz"}

For example: const char first[] = "foo"; char foo[][4] = {"bar", "foo", "", "baz"}

first将像这样存储在内存中:

first would be stored like this in memory:

{'f', 'o', 'o', '\0'}

foo的存储方式如下:

{'b', 'a', 'r', '\0', 'f', 'o', 'o', '\0', '\0', '\0', '\0', '\0', 'b', 'a', 'z', '\0'}

那你为什么要说这是整数呢?

So why would you say this is guaranteed for ints?

对于int[4]char[4]以及您可以想象的任何其他类型,都可以保证.

It is guaranteed for int[4], char[4] and any other type that you can imagine.

这篇关于是否保证子阵列线性分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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