将argv复制到新数组 [英] Copy argv into new array

查看:71
本文介绍了将argv复制到新数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码出现分段错误.有人可以解释为什么吗?我希望能够将argv的内容复制到一个名为rArray的新数组中.

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();
}

程序输出:

/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?

我得到了解决,将char **rArray更改为string rArray,然后从那里动态分配大小.

I got a fix, changing the char **rArray to string rArray, and dynamically allocating the size from there.

推荐答案

您需要为rArray分配内存,还需要初始化外部循环计数器i.

You need to allocate memory for rArray and also need to initialise the outer loop counter i.

由于argv的内容是常量字符串,因此您只需将指针复制到它们即可.

Since the contents of argv are constant strings, you could just 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退出条件)

Note that argv[argc] is guaranteed to be NULL. I've updated the loop to copy this as well (hence the unusual looking i<=argc exit condition)

如果您真的要复制字符串的内容(如minitech所建议的那样),则代码会变得更加复杂:

If you really want to copy the content of the strings (as minitech suggests), the code becomes a bit more complicated:

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;

这篇关于将argv复制到新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆