I'm getting a segmentation fault for the following code. Can somebody explain why? I would like to be able to copy the contents of argv into a new array, which I called rArray.
#include <iostream>
using namespace std;
int main( int argc, char **argv)
{
char **rArray;
int numRows = argc;
cout << "You have " << argc << " arguments:" << endl << endl;
cout << "ARGV ARRAY" << endl;
for (int i = 0; i < argc; i++)
{
cout << argv[i] << endl;
}
cout << endl << endl << "COPIED ARRAY" << endl;
for(int i; i < numRows; i++)
{
for (int j = 0; j < argc; j++)
{
rArray[i][j] = argv[i][j];
}
}
for (int i = 0; i < argc; i++)
{
cout << "Copied array at index " << i << "is equal to " << rArray[i] << endl;;
}
cin.get();
}
The program outputs :
/a.out hello world
You have 3 arguments:
ARGV ARRAY
./a.out
hello
world
COPIED ARRAY
Segmentation fault: 11
Why am I getting this error? How do I fix it?
EDIT: I got a fix, changing the char **rArray
to string rArray
, and dynamically allocating the size from there.
char** rArray
doesn’t allocate any memory for you, andj < argc
isn’t the right condition. – Wsanchar** rArray;
does allocate stack space (enough to hold a pointer). – Whisker