无法将"常量字符**"转换为"常量字符*"

cannot convert 'const char **' to 'const char*'

本文关键字:字符 常量 转换      更新时间:2023-10-16

大家早上好!我试图通过传递的'-e'参数从父程序创建fork/exec调用(例如parent -e child key1=val1…)。因此,我想将argv数组中前两个之后的所有值复制到一个新数组child_argv中。比如:

const char *child_argv[10];  // this is actually a global variable
static const char *sExecute;
      int I = 0;
const char *Value = argv[1];
    sExecute = Value;
      for (i=2; i<argc; i++) {
             child_argv[I] = argv[i];
             I++;
      }
    child_argv[I] = NULL;   // terminate the last array index with NULL

这样我就可以像这样调用执行端:

execl(sExecute, child_argv);

然而,我得到的错误信息"错误:不能转换'const char**'到'const char*'为参数'2'到'execl(const char*, const char*,…)'"。我甚至尝试使用中间步骤:

const char *child_argv[10];  // this is actually a global variable
static const char *sExecute;
      int I = 0;
const char *Value = argv[1];
    sExecute = Value;
      for (i=2; i<argc; i++) {
    const char *Value = argv[i+1];
             child_argv[I] = Value;
             I++;
      }
    child_argv[I] = NULL;   // terminate the last array index with NULL

但是我不明白。任何帮助将非常感激!

更新

正如所指出的,在这种情况下我应该使用'execv'而不是'execl'。

更新2

我最终复制了没有argv所需参数的数组。如何将数组的部分复制到另一个数组

From here: http://linux.die.net/man/3/exec

我想你的意思是叫"execv"而不是"execl"。Execl似乎接受可变数量的参数,期望每个const char *是另一个参数,而execv接受一个参数数组。

您应该使用execv。当您转换为execv时,由于某些原因,execv期望一个非const指针数组而不是const指针,因此您必须将数组强制转换为(char**)或将字符串复制到(char*)指针中。