数组是如何传递? [英] How are arrays passed?

查看:192
本文介绍了数组是如何传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由ref或值默认传递数组?
谢谢你。

Are arrays passed by default by ref or value? Thanks.

推荐答案

它们作为指针传递。这意味着,有关数组大小的所有信息都将丢失。你会好得多建议使用std ::载体,它可以通过值或引用传递,任你选择,因此它保留其所有信息。

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.

下面是传递一个数组给函数的例子。注意,我们必须专门指定元素的数量,作为的sizeof(p)的将使指针的大小

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 );
}

这篇关于数组是如何传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆