数组如何通过?

The*_* do 21 c++ arrays pointers pass-by-reference pass-by-value

数组是否默认通过ref或value传递?谢谢.

小智 29

它们作为指针传递.这意味着有关数组大小的所有信息都将丢失.建议您使用std :: vectors,它可以根据您的选择通过值或引用传递,从而保留所有信息.

这是将数组传递给函数的示例.注意我们必须具体指定元素的数量,因为sizeof(p)将给出指针的大小.

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 );
}
Run Code Online (Sandbox Code Playgroud)


fre*_*low 26

首先,在创建数组副本的意义上,您无法按值传递数组.如果您需要该功能,请使用std::vectorboost::array.

通常,指向第一个元素的指针按值传递.在此过程中,数组的大小会丢失,必须单独传递.以下签名都是等效的:

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!
Run Code Online (Sandbox Code Playgroud)

如果要通过引用传递,则大小是类型的一部分:

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

通常将传递引用与模板组合在一起,因此您可以使用具有不同静态已知大小的函数:

template<size_t size>
void by_reference(int (&a)[size]);
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.


Tho*_*ini 6

数组很特殊:它们总是作为指向数组第一个元素的指针传递.