1

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)); } } 
4
  • 1
    Is there a particular reason why you don't use myArray[i] = i Code looks much cleaner that way Commented Oct 8, 2016 at 5:34
  • Dynamic arrays are not allowed in C++. Commented Oct 8, 2016 at 5:35
  • Use a std::vector<int> instead. Commented Oct 8, 2016 at 5:35
  • 1
    Calling defineArray(myArray); doesn't modify myArray. Commented Oct 8, 2016 at 5:36

2 Answers 2

5

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) 
Sign up to request clarification or add additional context in comments.

Comments

-1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.