计算机(C编译器或其他东西)如何处理"自动数组声明"?| C语言

car*_*l13 2 c arrays memory-management sizeof dynamic-arrays

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


这让我很奇怪; 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;
}
Run Code Online (Sandbox Code Playgroud)

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

或者更一般地说:

sizeof(array)

在哪里array(N x type_size)

N是其中元素的数量array

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


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

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

AnT*_*AnT 6

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

你的声明

int array[] = {1,2,3};
Run Code Online (Sandbox Code Playgroud)

相当于

int array[3] = {1,2,3};
Run Code Online (Sandbox Code Playgroud)

意思是array有类型int[3].所以你sizeof(array)的解释是sizeof(int[3]),编译器立即知道.

sizeof我不知道也不关心你的任何"动态阵列".所有它关心的是在sizeof(ptr)运算符sizeof中应用于指针.所以它评估指针大小.