Copy argv to a new array

I get a segmentation error for the following code. Can someone explain why? I would like to be able to copy the contents of argv into a new array, which I named 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();
}

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 to fix it?

EDIT: I got a fix by changing char **rArrayto string rArrayand dynamically allocating the size from there.

+3
source share
3 answers

You need to allocate memory for rArrayand also initialize the external loop counter i.

Since the content argvis constant lines, you can simply copy pointers to them

rArray = new char*[argc+1];
for(int i=0; i <= argc; i++) {
    rArray[i] = argv[i];
}
// use rArray
delete [] rArray;

, argv[argc] NULL. , (, i<=argc)

( minitech), :

rArray = new char*[argc+1];
for(int i=0; i < argc; i++) {
    int len = strlen(argv[i]) + 1;
    rArray[i] = new char[len];
    strcpy(rArray[i], argv[i]);
}
rArray[argc] = NULL;
// use rArray
for(int i=0; i < argc; i++) {
    delete [] rArray[i];
}
delete [] rArray;
+9

; argv, std::vector std::string:

#include <string>
#include <vector>

int main( int argc, char **argv ) {
    std::vector<std::string> args( argv, argv + argc );
}
+8

Itโ€™s one thing that you donโ€™t initialize i

for(int i; i < numRows; i++)
        ^-- !

Secondly, rArraydoes not stand out

I suggest using std::vector<std::string>and copying all your arguments into a vector, you do not need to worry about allocating / freeing memory.

+3
source

All Articles