Why the size of malloc-ed array and non-malloced array are different? [duplicate]

▼魔方 西西 提交于 2019-12-24 07:40:12

问题


#include<stdio.h>
#include<stdlib.h>

int main (int argc, char *argv[]) {

    int* arr1 = (int*)malloc(sizeof(int)*4);
    int arr2[4];


    printf("%d \n", sizeof(arr1));
    printf("%d \n", sizeof(arr2));

    free(arr1);

    return 0;
}

Output

8
16

Why?


回答1:


Arrays are not pointers.

In your code, arr1 is a pointer, arr2 is an array.

Type of arr1 is int *, whereas, arr2 is of type int [4]. So sizeof produces different results. Your code is equivalent to

sizeof (int *);
sizeof (int [4]);

That said, sizeof yields the result of type size_t, so you should be using %zu to print the result.




回答2:


arr1 is a pointer when you call sizeof(arr1) this will you size of pointer. but arr2 represent block of memory for 4 integers.



来源:https://stackoverflow.com/questions/39444244/why-the-size-of-malloc-ed-array-and-non-malloced-array-are-different

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!