简体   繁体   中英

Number of array elementsbof dynamic allocated array in C

I have problems finding the number of array elements in my dynamical allocated array. If I have a normal Array I know how to find out how much elements are in there with:

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

printf("Number of array elements: %i\n",(int)(sizeof(array) / sizeof((array)[0])));

this prints me:

Number of array elements: 3

But when I want to dynamically allocate an array and know its size I can't get it working the same way:

int *array;

array = malloc(3*sizeof(int));
printf("Number of array elements: %i\n",(int)(sizeof(array) / sizeof((array)[0])));

This always gives me:

Number of array elements: 2

No matter how much how small or big I make the allocation it always prints

2

Please can someone help?

The reason you see different size is because the underlaying data isn't the same.

In you first example, you have statically compiled array of integers. This array elements are all aligned in memory and array is the array. Using sizeof(array) allows you to get the overall size of this array.

In the second example, you have a dynamically allocated pointer on an array of integers. This is totally different in memory. The array variable isn't the array practically speaking. It's the pointer to the first element. Using sizeof(array) here returns the size of the pointer on the first element, hence 8.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM