How are arrays passed?

情到浓时终转凉″ 提交于 2019-11-28 21:16:05

They are passed as pointers. This means that all information about the array size is lost. You would be much better advised to use std::vectors, which can be passed by value or by reference, as you choose, and which therefore retain all their information.

Here's an example of passing an array to a function. Note we have to specify the number of elements specifically, as sizeof(p) would give the size of the pointer.

int add( int * p, int n ) {
   int total = 0;
   for ( int i = 0; i < n; i++ ) {
       total += p[i];
   }
   return total;
}


int main() {
    int a[] = { 1, 7, 42 };
    int n = add( a, 3 );
}

First, you cannot pass an array by value in the sense that a copy of the array is made. If you need that functionality, use std::vector or boost::array.

Normally, a pointer to the first element is passed by value. The size of the array is lost in this process and must be passed separately. The following signatures are all equivalent:

void by_pointer(int *p, int size);
void by_pointer(int p[], int size);
void by_pointer(int p[7], int size);   // the 7 is ignored in this context!

If you want to pass by reference, the size is part of the type:

void by_reference(int (&a)[7]);   // only arrays of size 7 can be passed here!

Often you combine pass by reference with templates, so you can use the function with different statically known sizes:

template<size_t size>
void by_reference(int (&a)[size]);

Hope this helps.

Arrays are special: they are always passed as a pointer to the first element of the array.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!