简体   繁体   English

C中动态分配的数组的数组元素数

[英]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; int *数组;

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. 该数组元素都在内存中对齐 ,而array 数组。 Using sizeof(array) allows you to get the overall size of this array. 使用sizeof(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. array变量实际上不是数组。 It's the pointer to the first element. 它是指向第一个元素的指针。 Using sizeof(array) here returns the size of the pointer on the first element, hence 8. 在这里使用sizeof(array)返回第一个元素上指针的大小,因此为8。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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