problem with sizeof operator
void getSize(int *S1)
When you pass an array to this function, it decays to pointer type, so sizeof
operator will return the size of pointer.
However, you define your function as,
template<int N>
void getSize(int (&S1)[N])
{
//N is the size of array
int S_size1 = N;
int S_size2 = sizeof(S1)/sizeof(int); //would be equal to N!!
std::cout<<"array size(in function):"<<S_size1<<std::endl;
std::cout<<"array size(in function):"<<S_size2<<std::endl;
}
int S[]={1,2,3,2,5,6,25,1,6,21,121,36,1,31,1,31,1,661,6};
getSize(S); //same as before
then you can have the size of array, in the function!
See the demonstration yourself here : http://www.ideone.com/iGXNU
Inside getSize()
, you're getting size of pointer, which is 8 bytes (since you're probably running 64-bit OS). In main()
, you're getting size of array.
If you want to know array size, pass result of sizeof(S)
as additional argument to getSize()
.
More alternatives would be using some container (like std::vector
) or turning function into template function, as Nawaz proposed.
S
is an int *
, a pointer to an integer, which is a memory address, which is on your machine twice the size of an integer.
If you want the size of the array (I.e., the number of elements), you can't get that directly in pure C. But since this is a c++ question, there is a way: use a vector
, which has a size()
method.
Actually, this isn't quite true: within the function that you declare S
(and only if it's explicitly initialized at compile time as you do in your example -- even new int[19]
doesn't work), the sizeof
operator actually does get the correct answer, which is why c++ allows you to do this:
int S[]={1,2,3,2,5,6,25,1,6,21,121,36,1,31,1,31,1,661,6};
vector<int> v(S, S + sizeof(S) / sizeof(int) );
and then you can use v.size()
(see these docs).
The template version by Nawaz elsewhere is another excellent suggestion which forces the compiler into carrying the full information about the construction of the c++ array around (again, note that this is all known at compile time, which is why you can be explicit about the size in the argument).