c - "array"元素值是存储在一个位置还是不同的位置?

标签 c arrays pointers memory-layout

既然C语言中没有数组这样的东西,那么下面是全部存储在一个内存位置,还是每个元素的值都存储在内存位置的“数组”中?

int array[] = {11, 13, 17, 19};
  • 场景 1

    {11, 13, 17, 19} --> location A
    
  • 场景 2

    {
        11 --> location A
        13 --> location B
        17 --> location C
        19 --> location D
    }
    

哪个是有效的内存布局?

最佳答案

C 将“数组”明确定义为一种类型。

引用 C11,章节 §6.2.5,类型(强调我的)

An array type describes a contiguously allocated nonempty set of objects with a particular member object type, called the element type. The element type shall be complete whenever the array type is specified. Array types are characterized by their element type and by the number of elements in the array. An array type is said to be derived from its element type, and if its element type is T, the array type is sometimes called ‘‘array of T’’. The construction of an array type from an element type is called ‘‘array type derivation’’.

简而言之,答案是数组元素存储在单独但连续的位置。

假设我们声明了一个包含 5 个 int 的数组:

int arr[5];

然后,在整数大小为 2 个字节的平台上 (szeof(int) ==2),数组的元素将按如下方式组织:

enter image description here

在不同的平台上,sizeof(int) == 4,它可能是:

enter image description here

所以表示

{
    11 --> location A
    13 --> location B
    17 --> location C
    19 --> location D
}

是有效的,考虑到 B == A + 1C == B + 1 等等。

这里,请注意,指针运算与数据类型有关,因此 A+1 不会产生具有 1 byte 增量的地址,而是增量是由一个元素。换句话说,两个连续元素的地址之间的差异将与数据类型的大小相同 (sizeof (datatype))。

关于c - "array"元素值是存储在一个位置还是不同的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40364357/

相关文章:

c++ - 检测超出函数范围的未使用变量

c++ - sprintf_s 问题

c - 如何在c中返回指向可变大小的二维数组的指针

c - 使用不带循环的递归在 C 中编写程序以获得所需的输出

javascript - GAS 电子表格通过标记为 "SENT"来避免重复,不起作用?

c - 如何在c中的字符数组中用strtok划分单词

c++ - 如何从内存中删除动态添加的节点?

c++ - 在 C 中导航数组(性能)?

c - 如何使用strtok检测空行

c++ - 二叉搜索树 : Issue with Insert Function