如何获得“动态"数组的大小? [英] What should I do to get the size of a 'dynamic' array?

查看:82
本文介绍了如何获得“动态"数组的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码.

   int x[5];
   printf("%d\n",sizeof(x) );


   int *a;
   a = new int[3];
   printf("%d\n",sizeof(*a));

当我将一个静态"数组传递给sizeof()时,它将返回声明的数组的尺寸乘以该数据类型在内存中使用的字节数.但是,动态数组似乎有所不同.我的问题是我应该怎么做才能获得动态"数组的大小?

When I pass a 'static' array to sizeof(), it returns the dimension of the declared array multiplied by the number of bytes that the datatype uses in memory. However, a dynamic array seems to be different. My question is what should I do to get the size of an 'dynamic' array?

PD:可能与以下内容有关吗?

PD: Could it be related to the following?

int *a;
a=new int[3];
a[0]=3;
a[1]=4;
a[2]=5;
a[3]=6;

如果假设我在"a = new int [3]"中放置限制",为什么我可以修改第三个位置.

Why can I modify the third position if it's supposed I put a 'limit' in "a=new int[3]".

推荐答案

当我将一个静态"数组传递给sizeof()时,它将返回声明的数组的尺寸乘以该数据类型在内存中使用的字节数.

When I pass a 'static' array to sizeof(), it returns the dimension of the declared array multiplied by the number of bytes that the datatype uses in memory.

正确,这就是整个数组大小的计算方式.

Correct, that is how the size of the entire array is computed.

但是,动态数组似乎有所不同.

However, a dynamic array seems to be different.

这是因为您没有传递动态数组.您正在传递一个指针.指针是一种数据类型,其大小与它可能指向的内存块的大小无关,因此,您始终获得一个恒定值.为动态大小的内存块分配内存时,需要存储分配的大小以供将来参考:

This is because you are not passing a dynamic array; you are passing a pointer. Pointer is a data type with the size independent of the size of the block of memory to which it may point, hence you always get a constant value. When you allocate memory for your dynamically sized memory block, you need to store the size of allocation for future reference:

size_t count = 123; // <<== You can compute this count dynamically
int *array = new int[count];
cout << "Array size: " << (sizeof(*array) * count) << endl;

C ++ 14将具有可变长度的数组.当您检查 sizeof 时,这些数组将提供适当的大小.

C++14 will have variable-length arrays. These arrays will provide a proper size when you check sizeof.

可能与以下内容有关吗?[...]

Could it be related to the following? [...]

不,这无关.您的代码段显示了未定义的行为(写操作超出了分配的内存块的末尾),这意味着您的代码无效.它可能会立即崩溃,稍后导致崩溃或表现出其他任意行为.

No, it is unrelated. Your code snippet shows undefined behavior (writing past the end of the allocated block of memory), meaning that your code is invalid. It could crash right away, lead to a crash later on, or exhibit other arbitrary behavior.

这篇关于如何获得“动态"数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆