数组的C ++大小 [英] Size of an array C++
问题描述
可能重复:结果
的sizeof数组作为参数传递
块引用>我想知道为什么下面的code的输出为1和9是因为功能未申报大小的数组的?我怎样才能数组大小分开,一个功能?
的#includestdafx.h中
#包括LT&;&iostream的GT;
使用命名空间std;INT尺寸(int类型的[])
{
返回的sizeof一个/ sizeof的一个[0];
}诠释的main()
{
诠释一个[] = {} 5,2,4,7,1,8,9,10,6;
COUT<<大小(一)LT;< ENDL;
COUT<< sizeof的一个/ sizeof的一个[0]&下;&下; ENDL;
系统(暂停);
返回0;
}
解决方案当你写
尺寸(A)
然后你传递一个指针,而不是一个数组。由于指针的大小和INT
为4或8个(根据ABI),您将获得的sizeof(INT *)/ sizeof的INT
( 4月4日= 1 作为32位的机器和 8/4 = 2 作为64位的)这就是 1 或 2在C ++中,当传递一个数组作为参数传递给一个函数,其实你传递一个指针数组。
Possible Duplicate:
Sizeof array passed as parameterI was wondering why the output of the following code is 1 and 9. Is that because of undeclared array in function size? How can I separate "size of array" to a function?
#include "stdafx.h" #include <iostream> using namespace std; int size(int a[]) { return sizeof a/sizeof a[0]; } int main() { int a[] = {5,2,4,7,1,8,9,10,6}; cout << size(a) << endl; cout << sizeof a/sizeof a[0] << endl; system("pause"); return 0; }
解决方案When you write
size(a)
then you're passing a pointer and not an array. Since the size of a pointer and anint
is 4 or 8 (depending on ABI), you getsizeof(int *)/sizeof int
(4/4=1 for 32-bit machines and 8/4=2 for 64-bit ones) which is 1 or 2.In C++ when pass an array as an argument to a function, actually you're passing a pointer to an array.
这篇关于数组的C ++大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!