C++ 数组作为函数参数 [英] C++ arrays as function arguments
问题描述
- 我可以像处理 int 和 bool 等原语一样将数组传递给函数吗?
- 我可以按值传递它们吗?
- 函数如何知道它传递的数组的大小?
推荐答案
我可以将数组传递给函数吗我会使用诸如 int 之类的原语和布尔值?
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?
它没有.这就是使用 vector
之类的东西而不是 T *
之类的原因.
It doesn't. That's a reason to use things like vector<T>
instead of T *
.
澄清
一个函数可以接受一个特定大小的数组的引用或指针:
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;
}
不过,我很确定这不是 OP 想要的.
I'm pretty sure this is not what the OP was looking for, however.
这篇关于C++ 数组作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!