数组的大小 C++ [英] Size of an array C++
问题描述
可能的重复:
作为参数传递的数组大小
我想知道为什么以下代码的输出是 1 和 9.这是因为函数大小中未声明的数组吗?如何将数组大小"与函数分开?
I 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;
}
推荐答案
当您编写 size(a)
时,您传递的是指针而不是数组.由于指针和 int
的大小是 4 或 8(取决于 ABI),你得到 sizeof(int *)/sizeof int
(4/4=1 用于 32 位机器,8/4=2 用于 64 位机器),即 1 或 2.
When you write size(a)
then you're passing a pointer and not an array. Since the size of a pointer and an int
is 4 or 8 (depending on ABI), you get sizeof(int *)/sizeof int
(4/4=1 for 32-bit machines and 8/4=2 for 64-bit ones) which is 1 or 2.
在 C++ 中,当将数组作为参数传递给函数时,实际上是在传递指向数组的指针.
In C++ when pass an array as an argument to a function, actually you're passing a pointer to an array.
这篇关于数组的大小 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!