为什么不能通过将指针传递给函数来初始化数组? [英] Why can I not initialize an array by passing a pointer to a function?

查看:77
本文介绍了为什么不能通过将指针传递给函数来初始化数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个非常简单的解释,但是由于一段时间不用指针而被宠坏了.

I know this has a really simple explanation, but I've been spoiled by not having to use pointers for a while.

为什么我不能在c ++中做这样的事情

Why can't I do something like this in c++

int* b;
foo(b);

并通过...初始化数组.

and initialize the array through...

void Something::foo(int* a)
{
  a = new int[4];
}

在调用foo(b)之后,b仍然为空.为什么会这样?

after calling foo(b), b is still null. why is this?

推荐答案

将指针按值传递给函数 .本质上,这意味着将复制指针值(而不是pointee!).您修改的只是原始指针的副本.

Pointers are passed to the function by value. Essentially, this means that the pointer value (but not the pointee!) is copied. What you modify is only the copy of the original pointer.

有两种解决方案,都使用附加的间接层:

There are two solutions, both using an additional layer of indirection:

  1. 您都可以使用参考:

  1. Either you use a reference:

void f(int*& a) {
    a = new int[4];
}

  • 或者您传入一个指针到指针(对于您的情况而言,输出参数的常规性较差):

  • Or you pass in a pointer-to-pointer (less conventional for out parameters as in your case):

    void f(int** pa) {
       *pa = new int[4];
    }
    

    并像这样调用函数:

    f(&a);
    

  • 我个人不喜欢这两种样式:参数用于函数 input ,输出应由返回值处理.到目前为止,我还没有看到令人信服的理由来偏离C ++中的该规则.因此,我的建议是:使用以下代码代替.

    Personally, I dislike both styles: parameters are for function input, output should be handled by the return value. So far, I've yet to see a compelling reason to deviate from this rule in C++. So, my advise is: use the following code instead.

    int* create_array() {
        return new int[4];
    }
    

    这篇关于为什么不能通过将指针传递给函数来初始化数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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