将动态数组传递给其他函数的正确方式 [英] Proper way to pass dynamic arrays to other functions

查看:146
本文介绍了将动态数组传递给其他函数的正确方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  bool * used = new bool [长度](); 

我已经提出了几种编译方式,但我不太确定正确的方式是。



例如



这些是否按价值计算?

  static void test(bool arr [])

static void test(bool * arr)

这个通过参考吗?

  static void test(bool *& arr)

谢谢

解决方案

实际上,两个第一个想法通过地址传递数组,第三个通过引用传递数组。你可以设计一个小小的测试来检查:

  void test1(int * a){
a [0] = 1;
}

void test2(int a []){
a [1] = 2;
}

void test3(int *& a){
a [2] = 3;
}

int main(){
int * a = new int [3]();
a [0] = 0;
a [1] = 0;
a [2] = 0;

test1(a);
test2(a);
test3(a);

cout<<< a [0]< ENDL;
cout<<< a [1]< ENDL;
cout<<< a [2]< ENDL;
}

此测试的输出是

  1 
2
3

如果通过值传递参数,则不能在函数中修改参数,因为修改将保留在函数的范围内。在C ++中,数组不能被值传递,所以如果你想模拟这个行为,你必须传递一个 const int * 或一个 const int [] 作为参数。这样,即使数组通过引用传递,也不会因为 const 属性而在函数内部被修改。



为了回答你的问题,首选的方法是使用 std :: vector ,但如果你绝对想使用数组,你应该去 int *


What's the most "proper" way to pass a dynamically sized array to another function?

bool *used = new bool[length]();

I've come up with a few ways that compile but I'm not too sure on what the correct way is.

E.g.

Would these pass by value?

static void test(bool arr[])

static void test(bool *arr)

Would this one pass by reference?

static void test(bool *&arr)

Thanks

解决方案

Actually, the two first ideas pass the array by address and the third passes the array by reference. You can devise a little test to check this:

void test1(int* a) {
    a[0] = 1;
}

void test2(int a[]) {
    a[1] = 2;
}

void test3(int *&a) {
    a[2] = 3;
}

int main() {
    int *a = new int[3]();
    a[0] = 0;
    a[1] = 0;
    a[2] = 0;

    test1(a);
    test2(a);
    test3(a);

    cout << a[0] << endl;
    cout << a[1] << endl;
    cout << a[2] << endl;
}

The output of this test is

1
2
3

If a parameter is passed by value, it cannot be modified inside a function because the modifications will stay in the scope of the function. In C++, an array cannot be passed by value, so if you want to mimic this behaviour, you have to pass a const int* or a const int[] as parameters. That way, even if the array is passed by reference, it won't be modified inside the function because of the const property.

To answer your question, the preferred way would be to use a std::vector, but if you absolutely want to use arrays, you should go for int*.

这篇关于将动态数组传递给其他函数的正确方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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