Reputation: 1065
How do I make a correct function that receives array as an argument? In the code below, the result should be 36 but in my function in only shows 4. It seems like it only pass the first element.
void test(float v[]){
printf("size: %d\n", sizeof(v)); //RESULT: 4
}
int main(){
GLfloat vv[] = {
0, 0, 0,
1, 1, 0,
1, 0, 0
};
printf("size: %d\n", sizeof(vv)); //RESULT: 36
test(vv);
return 0;
}
Upvotes: 0
Views: 112
Reputation: 227390
How do I make a correct function that receives array as an argument?
If the array has a size known at compile time, as in your example, you can use a template function. This example takes the array elements by const reference:
template< class T, size_t N >
void foo( const T (&data)[N] )
{
// length of array is N, can access elements as data[i]
}
int main(){
GLfloat vv[] = {
0, 0, 0,
1, 1, 0,
1, 0, 0
};
foo(vv);
}
That was the literlal answer to the question. What I would do it use a type that has clear copy, assign and reference semantics, such as an std::array
:
template <size_t N>
void foo(const std::array<GLfloat, N>& data)
{
// data looks like a C array, but has size() and many other methods
}
int main(){
std::array<GLfloat, 9>{
{ 0, 0, 0,
1, 1, 0,
1, 0, 0 }
};
foo(vv);
}
Upvotes: 3
Reputation: 206518
When you pass array as an argument it decays as pointer to the first element.
sizeof
gives you size of the pointer not the array.
Simplest solutions is to pass the size as an separate argument to the function.
void myFunction(float[] array, size_t size);
Upvotes: 7