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)); } }
myArray[i] = iCode looks much cleaner that waystd::vector<int>instead.defineArray(myArray);doesn't modifymyArray.