问题
#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