Gunner Stone
Gunner Stone

Reputation: 1005

How to pass Dynamic Array by reference C++

I'm having trouble understanding how to pass a dynamic array by reference in C++.

I've recreated the problem in this small isolated code sample:

#include <iostream>

using namespace std;

void defineArray(int*);

int main()
{
    int * myArray;
    defineArray(myArray);

    /** CAUSES SEG FAULT*/
    //cout<<(*(myArray)); //desired output is 0
    return 0;
}

void defineArray(int*myArray)
{
    int sizeOfArray;
    cout<<"How big do you want your array:";
    cin>>sizeOfArray;

    /** Dynamically allocate array with user-specified size*/
    myArray=new int [sizeOfArray];

    /** Define Values for our array*/
    for(int i = 0; i < sizeOfArray; i++)
    {
        (*(myArray+i))=i;
        cout<<(*(myArray+i));
    }
}

Upvotes: 1

Views: 6599

Answers (2)

Christian Hackl
Christian Hackl

Reputation: 27528

This solution is hopelessly complicated. You don't need new[], pointers or even a reference parameter. In C++, the concept of "dynamic arrays" is best represented by std::vector, which you can just just use as a return value:

#include <iostream>
#include <vector>

std::vector<int> defineArray();

int main()
{
    auto myArray = defineArray();
    if (!myArray.empty())
    {
        std::cout << myArray[0] << "\n";;
    }
}

std::vector<int> defineArray()
{
    int sizeOfArray;
    std::cout << "How big do you want your array:";
    std::cin >> sizeOfArray;

    std::vector<int> myArray;
    for (int i = 0; i < sizeOfArray; i++)
    {
        myArray.push_back(i);
        std::cout<< myArray[i] << "\n";
    }
    return myArray;
}

push_back will work intelligently enough and not allocate new memory all the time. If this still concerns you, then you can call reserve before adding the elements.

Upvotes: -1

songyuanyao
songyuanyao

Reputation: 172894

myArray is passed by value itself, any modification on myArray (such as myArray=new int [sizeOfArray];) has nothing to do with the original variable, myArray in main() is still dangled.

To make it passed by reference, change

void defineArray(int*myArray)

to

void defineArray(int*& myArray)

Upvotes: 5

Related Questions