問題描述
可能的重復:
函數參數中數組的長度
我正在做作業,我完全被難住了.我們假設列表的每個順序都是一個整數數組,所以我根據老師的偽代碼編寫了這段代碼:
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)
{
...
}
即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()
- @sehe 建議的模板解決方案
- 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
這篇關于作為函數參數傳遞的數組的大小的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!