sizeof作为函数参数传递的数组 [英] sizeof an array passed as 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
不确定是 sizeof(v)/ sizeof(int)
是正确的方法。
The only thing I am not sure of is if sizeof(v)/sizeof(int)
is the right way to go.
推荐答案
sizeof(v)/ sizeof(int)
不是要走的路。您的函数完全等效于:
sizeof(v)/sizeof(int)
is not the way to go. Your function is exactly equivalent to:
void permute(int *v, int curr, char *letters)
{
...
}
ie v
不是一个真正的数组,它是一个指针。您不能以C或C ++传递数组。
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
),您可以调用size()
- 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 callsize()
on - the template solution that @sehe suggests
这篇关于sizeof作为函数参数传递的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!