C++ arrays as function arguments

2020-01-31 03:23发布

  • 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?

8条回答
聊天终结者
2楼-- · 2020-01-31 04:23

You can pass arrays the usual way C does it(arrays decay to pointers), or you can pass them by reference but they can't be passed by value. For the second method, they carry their size with them:

template <std::size_t size>
void fun( int (&arr)[size] )
{
   for(std::size_t i = 0; i < size; ++i) /* do something with arr[i] */ ;
}

Most of the time, using std::vector or another sequence in the standard library is just more elegant unless you need native arrays specifically.

查看更多
做自己的国王
3楼-- · 2020-01-31 04:25

Can I pass arrays to functions just as I would do with primitives such as int and bool?

Yes, you can. Passing an array name as an argument to a function passes the address of the first element.

In short:

void foo(int a[]);

is equivalent to

void foo(int * a);

Can I pass them by value?

Not really. The "value" that gets passed with an array name is the address of the first element.

The only way to pass a copy of a C-style array is to wrap it in a class or struct that implements deep-copy semantics.

How does the function know of the size of the array it is passed?

It doesn't, unless you have your function take in an additional parameter that is the size of the array.

查看更多
登录 后发表回答