Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

size of array passed to C++ function? [duplicate]

Tags:

c++

arrays

Possible Duplicate:
determine size of array if passed to function

How can I get the size of a C++ array that is passed to a function?

In the following code, the sizeof(p_vertData) does not return the correct size of the array.

float verts[] = {
 -1.0,1.0,1.0,
 1.0,1.0,1.0,
 1.0,-1.0,1.0,
 -1.0,-1.0,1.0,

 -1.0,1.0,-1.0,
 1.0,1.0,-1.0,
 1.0,-1.0,-1.0,
 -1.0,-1.0,-1.0
};

void makeVectorData(float p_vertData[]) {   
 int num = (sizeof(p_vertData)/sizeof(int)); 
 cout << "output: " << num << endl;
}; 

What am I doing wrong?

like image 874
qutaibah Avatar asked Jun 17 '10 13:06

qutaibah


2 Answers

You can't - arrays decay to pointers when passed as function parameters so sizeof is not going to help you.

like image 99
Paul R Avatar answered Oct 09 '22 02:10

Paul R


If you don't mind templates, you can do as follows. Note that it will work only if the array size is known at compile time.

template <int N>
void makeVectorData(float (&p_vertData)[N]) {   
 int num = (sizeof(p_vertData)/sizeof(p_verData[0])); 
 cout << "output: " << num << endl;
};

Beware also that you should divide sizeof(array) by an array element size. In your example, you're dividing the size of an array of float by the size of an integer.

like image 44
Didier Trosset Avatar answered Oct 09 '22 02:10

Didier Trosset