Possible Duplicate:
length of array in function argument
Hi am doing homework and I am completly stumped. We were suppose to get every order of a list an array of integers so I wrote this piece of code, based off of my teacher's pseudocode:
void permute(int v[], int curr,char letters[])
{
if(curr >= sizeof(v)/sizeof(int))
{
checkit(v,letters);
}
for(int i = curr; i < sizeof(v)/sizeof(int); i++)
{
swap(i,curr,v);
permute(v,curr + 1,letters);
swap(v[curr],v[i]);
}//for
}//permu
The only thing I am not sure of is if sizeof(v)/sizeof(int)
is the right way to go.
The function clear() uses the idiom sizeof(array) / sizeof(array[0]) to determine the number of elements in the array. However, array has a pointer type because it is a parameter. As a result, sizeof(array) is equal to the sizeof(int *) .
Using sizeof directly to find the size of arrays can result in an error in the code, as array parameters are treated as pointers.
The sizeof() operator returns pointer size instead of array size. The 'sizeof' operator returns size of a pointer, not of an array, when the array was passed by value to a function. In this code, the A object is an array and the sizeof(A) expression will return value 100.
Using sizeof() function to Find Array Length in C++ The sizeof() operator in C++ returns the size of the passed variable or data in bytes.
sizeof(v)/sizeof(int)
is not the way to go. Your function is exactly equivalent to:
void permute(int *v, int curr, char *letters)
{
...
}
i.e. v
is not really an array, it's a pointer. You cannot pass arrays in C or C++.
The solution is one of the following (not exhaustive):
std::vector
), which you can call size()
onOne of my pet peeves: you can get C++ to deduce the array size for you
template <size_t N>
void permute(int (&v)[N], int curr,char letters[])
{
if(curr >= N)
{
checkit(v,letters);
}
for(int i = curr; i < N; i++)
{
swap(i,curr,v);
permute(v,curr + 1,letters);
swap(v[curr],v[i]);
}//for
}//permu
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