C ++数组作为函数参数 [英] C++ arrays as function arguments
问题描述
- 我可以通过阵列功能,就像我将与原语,如int和布尔办?
- 我可以按值传递呢?
- 如何函数知道数组的大小是通过呢?
我可以通过阵列功能一样
我将与原语如int做
和布尔?
块引用>可以,但只能使用指针(即:由参考)
。
我可以按值传递呢?
块引用>没有。您可以创建支持类,但普通阵列没有。
如何功能知道它是通过在阵列的大小?
块引用>它没有。这是一个理由去使用的东西,像
矢量< T>
而不是T *
澄清
一个函数可以接受引用或指向特定大小的数组:
无效FUNC(CHAR(* P)[13])
{
为(中间体n = 0时; Nδ13 ++ n)的
的printf(%C,(* p)的[N]);
}诠释的main()
{
所以char a [13] =你好,世界;
FUNC(&放大器;一个); 焦B〔5] =糟糕;
//下一行不会编译
// FUNC(和b); 返回0;
}我是pretty肯定这不是什么OP不过是寻找。
- Can I pass arrays to functions just as I would do with primitives such as int and bool?
- Can I pass them by value?
- How does the function know of the size of the array it is passed?
解决方案Can I pass arrays to functions just as I would do with primitives such as int and bool?
Yes, but only using pointers (that is: by reference).
Can I pass them by value?
No. You can create classes that support that, but plain arrays don't.
How does the function know of the size of the array it is passed?
It doesn't. That's a reason to use things like
vector<T>
instead ofT *
.Clarification
A function can take a reference or pointer to an array of a specific size:
void func(char (*p)[13]) { for (int n = 0; n < 13; ++n) printf("%c", (*p)[n]); } int main() { char a[13] = "hello, world"; func(&a); char b[5] = "oops"; // next line won't compile // func(&b); return 0; }
I'm pretty sure this is not what the OP was looking for, however.
这篇关于C ++数组作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!