【问题标题】:C++ Array as reference or as pointerC++ 数组作为引用或指针
【发布时间】:2017-02-05 15:00:49
【问题描述】:

在这个程序中有两个函数:一个是创建一个数组,另一个是删除它

#include "stdafx.h"
#include <iostream>
using namespace std;

void create_array(int **&arr,int nrow, int ncol) {
    arr = new int*[nrow];
    for (int i = 0; i < nrow; ++i){
        arr[i] = new int[ncol];
        }
}

void clean_memory(int **&arr, int nrow, int ncol) {
    for (int i = 0; i < nrow; ++i) {
        delete[] arr[i];
    }
    delete[] arr;
}


int main()
{
    int nrow, ncol,element;
    int **arr;
    printf("Dynamic array \n");
    printf("Write down number of rows and number of columns \n");
    scanf_s("%d %d", &nrow, &ncol);
    create_array(arr,nrow, ncol);
    clean_memory(arr, nrow, ncol);
    cin.get();
    printf("Press Enter to exit \n");
    cin.get();

    return 0;
}

为什么我们将数组作为引用传递给create_array,但我们不能作为指针传递(没有&amp;)?

为什么我不能这样写:

void create_array(int **arr,int nrow, int ncol)

clean_memory 也是如此

【问题讨论】:

  • 您使用可变长度 C 数组而不是 std::vector 是否有原因?
  • @Corristo 可变长度 C 数组未在此处使用。 new 是一个 C++ 特性
  • 哦,确实:D该睡觉了。

标签: c++ arrays pointers reference pass-by-value


【解决方案1】:
int **arr

是一个表示int地址的值,

如果你用这种类型的参数调用函数,它会按值传递,这意味着该函数具有源值的离散本地副本。

由于函数的目的是为我们提供这种类型的值,因此它需要返回这样的值、获取 dest 变量的地址或获取引用。

int **arr = get(...);
get(&arr, ...);
// or opaquely by reference
get(arr, ...);

【讨论】:

    【解决方案2】:

    为什么我不能这样写:

    void create_array(int **arr,int nrow, int ncol)
    

    你终于想要了

    int **arr;
    

    接收在main() 中分配给create_array() 的值,这就是它传递给的原因

    void create_array(int **&arr,int nrow, int ncol)
    

    作为参考。

    实际上并不需要作为参考传递

    void clean_memory(int **&arr, int nrow, int ncol)
    

    除非你想在删除后将输出参数设置为nullptr

    void clean_memory(int **&arr, int nrow, int ncol) {
        for (int i = 0; i < nrow; ++i) {
            delete[] arr[i];
        }
        delete[] arr;
        arr = nullptr; // <<<<<<<<<<<<<<<<<<<<<
    }
    

    【讨论】:

      【解决方案3】:

      如果您以create_array(int **arr,int nrow, int ncol) 作为签名调用createArray(arr,nrow, ncol)arr 将不会在main 函数中更新。它将保持其未定义的值。

      即使在C 中,您也必须调用createArray(&amp;arr,nrow, ncol) 才能在调用者级别更新arrC++ 授权通过 ref 调用以简化阅读,但生成的代码将与通过值传递 &amp;arr 相同。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-04-07
        • 1970-01-01
        • 2012-02-27
        • 1970-01-01
        • 2021-07-03
        • 2018-01-04
        • 2011-05-24
        相关资源
        最近更新 更多