Possible Duplicate:
Sizeof array passed as parameter
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;
}
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.
In C++ when pass an array as an argument to a function, actually you're passing a pointer to an array.
Maroun85 answer is correct. This is not obvious but a
in int size(int a[])
is a pointer.
But why don't you do it the c++ way. Using std::vector
s
std::vector<int> a = {5,2,4,7,1,8,9,10,6};
cout << a.size() << endl;
no tricks here
-- edit
If your compiler does not support c++11. You can do:
std::vector<int> a;
a.push(5);
a.push(2);
...
cout << a.size() << endl;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With