I am trying to do the following:
Read a text file containing integer data using a function such that the code doesn’t mess up my main function and then parsing the data to the main function.
my code looks like this
void Readata(char* fname, int* n, int* TheArray){
int nn=0;
int anyInt=0;
ifstream InFile( fname );
if ( ! InFile.is_open() ) throw myErrHandler("Could not open input file");
InFile >> anyInt;
if ( ! InFile ) throw myErrHandler( "Could not read size of array" );
nn=anyInt;
(*n)=nn;
int* AnArray = (int*) calloc(nn,sizeof(int));
for(int i=0; i<nn; i++){
InFile >> anyInt;
if ( !InFile ) throw myErrHandler( "Could not read data" );
AnArray[i]=anyInt;
}
TheArray = AnArray;
}
And the main function looks like
int main(int argc, char **argv){
if ( argc < 2 ){
cerr << "Usage: " << argv[0] << " input file" << endl;
return 777;
}
int n;
int* TheArray;
ReadData(arg[1], &n, TheArray);
return 1;
}
My problem is, that when I try to access TheArray from the main function, I get a “Segmentation fault (core dumped)” message. Obviously, I do not point to the right place with the “TheArray” pointer after the ReadData function has been called. If I print the data to the screen in the ReadData function, both AnArray and TheArray points to the same (and the right thing). What is the right way to do this?
When you call
ReadDatatheTheArraypointer is passed by value, so inside the function it behaves like any other non-pointer argument which means changes to it will not be visible outside the function. You have to pass the actual pointer as a reference (i.e. the address of the pointer) for the argument to change it:And call it like
Edit: Using the suggestion in the comment from Pete is probably better. However, even better would be to stop using raw pointers at all, and start using
std::vector.