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

查看:24
本文介绍了将 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天全站免登陆