gpt4 book ai didi

C++ 数组作为函数参数

转载 作者:可可西里 更新时间:2023-11-01 16:24:18 24 4
gpt4 key购买 nike

  • 我能否像处理 int 和 bool 等基元一样将数组传递给函数?
  • 我可以按值传递它们吗?
  • 函数如何知道传递给它的数组的大小?

最佳答案

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?

事实并非如此。这就是使用 vector<T> 之类的东西的原因而不是 T * .

澄清

一个函数可以接受一个指向特定大小数组的引用或指针:

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 想要的。

关于C++ 数组作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2867783/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com