gpt4 book ai didi

c - 计算机(C 编译器或其他)如何处理 "automatic array declaration"? | C语言

转载 作者:行者123 更新时间:2023-12-04 10:43:20 25 4
gpt4 key购买 nike

我试图从一个函数返回一个动态声明的数组;到目前为止,我正在返回一个结构来保存指向内存块的指针,该内存块由 malloc() 分配给数组 AND 一个整数来存储数组的长度。


这让我想知道; C 编译器(或其他)如何处理程序中声明的自动数组?例如。

main()
{
//delcare an array holding 3 elements
int array[] = {1,2,3};


/*variable to hold length of array
*size of array / size of 1st element in the array == length of the array
*this will == 3
*/
int array_Length = (sizeof(array))/(sizeof(*array));


//call malloc for a block of memory to hold 3 integers(worth of memory)
int* ptr = malloc(3*(sizeof(int)));


/*not exactly sure what this formula means when using a pointer???
*but it seems to always == 1
*/
int dynamic_array_length = (sizeof(ptr))/(sizeof(*ptr));

return 0;
}

我的观点是sizeof() 运算符以某种方式知道自动声明的数组 有 3 个整数在里面。

或者更一般的:

sizeof(数组)

其中 array 是 (N x type_size)

N数组

中元素的数量

type_size是用来存储数据类型的内存字节数


自动数组是否存储了有关其大小/长度的附加信息?

动态数组的存储方式不同吗?(我知道我们控制何时从内存中释放动态变量)

最佳答案

运算符 sizeof 是一个编译时构造(VLA 参数除外)。它以字节为单位告诉您对象大小,因为它知道确切的编译时对象类型。当您知道确切的类型时,大小也会立即知道。无需在任何地方单独存储元素的数量。

您的声明

int array[] = {1,2,3};

相当于

int array[3] = {1,2,3};

表示 array 的类型为 int[3]。所以你的 sizeof(array) 被解释为 sizeof(int[3]),编译器立即知道它。

sizeof 不知道也不关心您的任何“动态数组”。它只关心 sizeof(ptr) 运算符 sizeof 应用于指针。因此它计算为指针大小。

关于c - 计算机(C 编译器或其他)如何处理 "automatic array declaration"? | C语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35305559/

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