sizeof an array passed as function argument [dupli

2019-01-12 09:06发布

问题:

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.

回答1:

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


回答2:

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


回答3:

In addition to Oli's answer: the typical way in C++ is to pass a pointer to the beginning and a pointer to the end of the sequence that you want to permute. By convention the beginning pointer is inclusive, the ending pointer is exclusive.

void permute(int *v, int *begin, int *end, char *letters) {
  if (begin == end) {
    checkit(v, end, letters);
  } else {
    ...
    permute(v, begin + 1, end, letters);
    ...
  }
}


标签: c++ recursion