本文介绍了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,

推荐答案

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.


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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 15:35
查看更多