2013-04-12 193 views
4

我目前正在写我的课是应该作为一个很基本的壳转让。我差不多完成了,但是我遇到了execvp和我的字符数组参数问题。这是我的代码的一小段代码。C++为const char *为const char * const的

//Split the left content args 
istringstream iss(left); 
while(getline(iss, s, ' ')){ 
    v.push_back(s); 
} 

//Get the split string and put it into array 
const char* cmd_left[v.size()+1]; 
for(unsigned int i = 0; i < v.size(); i++){ 
    cmd_left[i] = v.at(i).c_str(); 
} 
cmd_left[v.size()] = 0; 
v.clear(); 

,这是由...

execvp(cmd_left[0], cmd_left); 

利用我的错误是

assign3.cxx:96:34: error: invalid conversion from ‘const char**’ to ‘char* const*’ [-fpermissive] 

我明白,问题是,我的字符数组没有满常量数据,所以我需要从const char*const char* const。我读了一些关于const_cast的内容,但我不确定这是否是我需要做的。

如果你会这么好心,你能不能帮我把我的字符数组的数组通过该功能可以正确地接受?如果您需要我发布更多我的代码,请告诉我。

感谢

回答

1

问题是你不能传递常量变量函数期望非const参数。

换句话说,const char *char *一个子集。

删除const

/*const*/ char* cmd_left[v.size()+1]; 

添加const_cast这里

cmd_left[i] = const_cast<char *>(v.at(i).c_str()); 

你的代码的其他部分看起来很可疑,但是这将使得编译

+0

啊,非常感谢你。这样做更有意义。另外,我的代码的其余部分只是将字符串拆分为更易于管理的形式。也许有更好的办法,但它完成了任务,所以我很满足。 – Zerocaliber

+0

@ user2272616欢迎您。 – yngccc

0

没有任何的const_cast:

istringstream iss(left); 
while(getline(iss, s, ' ')){ 
    v.push_back(s); 
} 

//assuming v is not empty! which you were already 
string command = v[0]; //store the command in a separate variable (this makes a copy of the string) 

char* cmd_left[v.size()+1]; //not a (const char)* 
for(unsigned int i = 0; i < v.size(); i++){ 
    cmd_left[i] = new char[v[i].size()+1]; 
    strcpy(cmd_left[i], v[i].c_str()); //copy contents of each string onto a new buffer 
} 
cmd_left[v.size()] = NULL; 

v.clear(); //if you really want to; not necessary from the code you posted 

//... 
execvp(command.c_str(), cmd_left); 
+0

v.clear()实际上最终是必需的,因为我稍后重新使用它。不过谢谢你给我演示如何在不投射的情况下做到这一点。 – Zerocaliber

0

这是不容易,有时不可能产生元件的常量动态数组,因为所有元件必须初始化中声明的{}。 但幸运的是,您可以告诉编译器,您传递的数组将至少在特定的持续时间内为const。你可以做到以下几点:

&((char* const) (const_cast<char*>(cmd_left[0]))) 

const_cast里面会去掉字符数组的常量std :: string是拥有的。所以,函数很可能会改变std :: string后面的字符数组的内容。当知道这些参数的函数的行为是已知的,那么这可能是好的。

如果你想创建的char *的常量数组,而无需使用新诉诸的const_cast或管理内存/删除,你可以使用std ::矢量>而不是字符串的载体。

istringstream iss(left); 
while(getline(iss, s, ' ')){ 
    v.push_back(std::vector<char>(s.length()+1)); 
    strcpy(&v.back().front(),s.c_str()); 
} 

//Get the split string and put it into array 
char* cmd_left[v.size()+1]; 
for(unsigned int i = 0; i < v.size(); i++){ 
    cmd_left[i] = &v.at(i).front(); 
} 
cmd_left[v.size()] = 0; 
v.clear(); 
execvp(cmd_left[0], &((char* const)cmd_left[0])); 

希望这会有所帮助。