我目前正在为我的类写一个作业,它应该作为一个非常基本的shell。我几乎完成了,但是我遇到了execvp和我的字符参数数组的问题。下面是我的代码的一小段。
//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的东西,但我不确定这是否是我需要做的。
如果你愿意的话,你能帮我让我的字符数组被这个函数正确地接受吗?如果你需要我发布更多的代码,请让我知道。
谢谢
发布于 2013-04-12 10:04:45
问题是你不能将常量变量传递给期望非常量参数的函数。
换句话说,const char *是char *的一个子集。
删除const
/*const*/ char* cmd_left[v.size()+1];在此处添加const_cast
cmd_left[i] = const_cast<char *>( v.at(i).c_str() );代码的其他部分看起来很可疑,但这将使其编译
发布于 2013-04-12 10:22:31
不带任何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);发布于 2013-04-12 10:50:46
创建元素的常量动态数组并不容易,有时甚至是不可能的,因为所有元素都必须在初始化器{}中声明。但幸运的是,你可以告诉编译器,你传递的数组将是常量的,至少在一定的持续时间内是常量。您可以执行以下操作,这将产生以下结果
&((char* const) (const_cast<char*>(cmd_left[0]) ))其中的const_cast将删除std::string所拥有的字符数组的不变性。因此,函数很可能会更改std::string后面的字符数组的内容。当函数接受这样的参数的行为是已知的,那么这可能是正确的。
如果您希望创建char*的常量数组,而不使用const_cast或使用new/delete管理内存,则可以使用std::vector >代替字符串向量。
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]));希望这能有所帮助。
https://stackoverflow.com/questions/15961715
复制相似问题