c ++,sizeof(array)arraysize [英] c++, sizeof(array) arraysize

查看:127
本文介绍了c ++,sizeof(array)arraysize的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



i输入以下代码:

Hi,
i type the code below:

int arraysize;
    std::cin>>arraysize;
    int* arr=new int[arraysize];
    std::cout<<sizeof(arr)<<" - "<<arraysize;



我输入9作为数组大小。

但它打印4 - 9.



我想得到元素的数量。



谢谢,


I enter 9 as the arraysize.
but it prints 4 - 9.

I want to get number of the elements.

Thanks,

推荐答案

你正在绊倒C ++语言的两个微妙之处:



(1)当你动态地(通过new)分配一个数组时你的商店会指向第一个元件。但是该指针不再包含数组的长度。如果你要求sizeof arr,你将获得该指针的大小而不是数组的大小。你是否已将数组定义为



You are stumbling over two subtleties of the C++ language:

(1) When you allocate an array dynamically (by new) your store a pointer to the first element. But that pointer no longer contains the length of the array. If you ask for "sizeof arr" you will get the size of that pointer and not the size of the array. Had you defined your array as

int myArray [10];





然后sizeof myArray将以字节为单位返回数组的大小。



(2)您混淆了元素的数量和数组的字节长度。您的arraysize变量包含元素数。以字节为单位的数组大小将是x倍大,x是单个int变量的长度。



then "sizeof myArray" would return the size of the array in bytes.

(2) You are confusing the number of elements and the length in bytes of an array. Your arraysize variable hold the number of elements. The size of the array in bytes would be x-times larger, x being the length of a single int variable.






很简单。通过 sizeof(arr)你只是要求 POINTERG TO INT 的大小,因为 arr 是指向int的指针(参见声明 int * arr )。 32b操作系统上指针的大小总是4B(32b)。



如果你想以字节打印整个数组的大小,你必须将单个字节的大小乘以数组的长度:

Hi,

it is simple. By sizeof(arr) You are just asking what is the size of POINTERG TO INT, because arr is pointer to int (see declaration int* arr). And the size of a pointer is always 4B (32b) on 32b OS.

If you want to print out the size of the whole array in bytes, you have to multiply the size of a single byte by the lenght of the array:
int arraysize;
std::cin >> arraysize;
int* arr = new int[arraysize];
std::cout<< sizeof(int)*arraysize <<" - "<<arraysize;



希望这会有所帮助。



祝你好运,

JK


Hope this helps.

Best regards,
J.K.


如果声明一个静态数组
int arr[9]

然后你可以使用 _countof()宏来获取数组中的元素数量。使用动态分配的数组是不可能的。那些你必须跟踪自己。

then you can use the _countof() macro to get the number of elements in the array. It is impossible to do that with a dynamically allocated array. Those you have to keep track of yourself.


这篇关于c ++,sizeof(array)arraysize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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