C++中动态数组的长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11760521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:30:50  来源:igfitidea点击:

length of dynamic array in c++

c++arraysdynamic-arrays

提问by Jatin

Possible Duplicate:
How to find the sizeof(a pointer pointing to an array)

可能的重复:
如何找到 sizeof(指向数组的指针)

I declared a dynamic array like this:

我声明了一个这样的动态数组:

int *arr = new int[n];   //n is entered by user 

Then used this to find length of array:

然后用它来查找数组的长度:

int len = sizeof(arr)/sizeof(int);

It gives lenas 1instead of n. Why is it so?

它给出lenas1而不是n。为什么会这样?

回答by Andrew

Because sizeofdoes not work for dynamic arrays. It gives you the size of pointer, since int *arris a pointer

因为sizeof不适用于动态数组。它为您提供 的大小pointer,因为它int *arr是一个指针

You should store the size of allocated array or better use std::vector

您应该存储分配数组的大小或更好地使用 std::vector

回答by yuri kilochek

Because arris not an array, but a pointer, and you are running on an architecture where size of pointer is equal to the size of int.

因为arr不是数组,而是指针,并且您正在运行在指针大小等于int.

回答by Scientist42

Andrew is right. You have to save nsomewhere (depends on where do you use it). Or if you are using .NET you could use Array or List...

安德鲁是对的。您必须将n保存在某个地方(取决于您在哪里使用它)。或者,如果您使用的是 .NET,则可以使用 Array 或 List ...