为什么malloc-ed数组和非malloc数组的大小不同? [英] Why the size of malloc-ed array and non-malloced array are different?
本文介绍了为什么malloc-ed数组和非malloc数组的大小不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#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;
}
输出
8
16
为什么?
推荐答案
在您的代码中,arr1
是一个指针,arr2
是一个数组.
In your code, arr1
is a pointer, arr2
is an array.
arr1
的类型是int *
,而arr2
是int [4]
类型.因此sizeof
会产生不同的结果.您的代码等同于
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]);
也就是说,sizeof
会产生类型为size_t
的结果,因此您应该使用%zu
来打印结果.
That said, sizeof
yields the result of type size_t
, so you should be using %zu
to print the result.
这篇关于为什么malloc-ed数组和非malloc数组的大小不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文