Possible Duplicates:
Sizeof an array in the C programming language?
determine size of array if passed to function


how can I get the size of an array that is passed to a function ? I have this code, but it is not working for me

float verts[] = {


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


+1  A: 

You can't divide by sizeof(float) if the array is not generated at compile time. However, in this case, it is, so the compiler is aware of the size of the array. Something to keep in mind.

Stefan Valianu
+3  A: 

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

Paul R
+3  A: 

In your example, it is effectively passing a pointer to the method; there is no size information. It would be necessary to pass the size from the calling method.

Mark Wilkins
+2  A: 

You cannot pass a vector as argument to a function.

Actually, you can, but the function always accepts it as a pointer (to the first element), regardless of whether you write (float *data) or (float data[]).

Pass the size as a separate argument, using sizeof(verts)/sizeof(verts[0]).

+2  A: 

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.

Didier Trosset
Why don't you use simply the N parameter?
I could, I should have. But I prefer in the present case to show a code sample that is as close as possible to the question.
Didier Trosset

By using templates:

void do_somthing( Type* pointer, size_t size ){ }; // nomal funciton

template < int size >
inline void do_somthing( Type (&array) [ size ] ) // this is tricky,
    do_somthing( array, size );

Type data[10];

You need this trick with reference to prevent array being implict casted to pointer. Extra tamplate is to prevent orginal function being linked many times with only one data changed.