Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem with sizeof operator

Tags:

c++

arrays

sizeof

As i want to find array size dynamically in function, i used sizeof operator. But i got some unexpected result. here is one demo program to show you, what i want to do.

//------------------------------------------------------------------------------------------
#include <iostream>

void getSize(int *S1){

    int S_size = sizeof S1/sizeof(int);
    std::cout<<"array size(in function):"<<S_size<<std::endl;
}

int main(){

    int S[]={1,2,3,2,5,6,25,1,6,21,121,36,1,31,1,31,1,661,6};
    getSize(S);
    std::cout<<"array size:"<<sizeof S/sizeof(int)<<std::endl;
    return 0;
}
//------------------------------------------------------------------------------------------

compilation command : g++ demo1.cc -o demo1 {fedora 12}

output:

array size(in function):2
array size:19

please explain ,why this is happening. what can be done to solve this problem.

like image 564
White Dwarf Avatar asked Dec 10 '22 11:12

White Dwarf


1 Answers

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

like image 128
Nawaz Avatar answered Dec 22 '22 12:12

Nawaz