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?
You can't - arrays decay to pointers when passed as function parameters so sizeof
is not going to help you.
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.
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