Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof an array passed as function argument [duplicate]

Tags:

c++

recursion

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.

like image 803
Travis Pessetto Avatar asked Nov 24 '11 00:11

Travis Pessetto


People also ask

How do you determine the size of an array as a parameter?

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 *) .

Can the sizeof operator be used to tell the size of an array passed to a function?

Using sizeof directly to find the size of arrays can result in an error in the code, as array parameters are treated as pointers.

Does sizeof return array size?

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.

How do I get the size of an array passed to a function in C++?

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.


2 Answers

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):

  • add an extra argument that explicitly describes the length of the array
  • add an extra argument that points at the last element of the array
  • use a proper container (e.g. std::vector), which you can call size() on
  • the template solution that @sehe suggests
like image 110
Oliver Charlesworth Avatar answered Sep 22 '22 05:09

Oliver Charlesworth


One 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
like image 23
sehe Avatar answered Sep 24 '22 05:09

sehe