Search code examples
c++arrayspointersreferencepass-by-value

C++ Array as reference or as pointer


In this program there is 2 functions: one to create an array, and another to delete it

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

Why are we passing array to create_array as a reference, but we can't pass as pointer ( without &)?

Why can't i write like this:

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

Same goes for clean_memory


Solution

  • Why can't i write like this:

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

    You finally want

    int **arr;
    

    to receive a value that was allocated in create_array() in main(), that's why its passed to

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

    as reference.

    It's not really needed to pass as reference to

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

    unless you want to set the output parameter to nullptr after deleting:

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