繁体   English   中英

C ++ const char * to const char * const

[英]C++ const char* To const char* const

我目前正在为我的班级写一个作为一个非常基本的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 ,但我不确定这是否是我需要做的。

如果你会这么善良,你能帮助我让我的数组字符数组被该函数正确接受吗? 如果您需要我发布更多我的代码,请告诉我。

谢谢

问题是你不能将const变量传递给期望非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() );

代码的其他部分看起来很可疑,但这会使它编译

没有任何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);

要创建一个const动态元素数组并不容易,因为所有元素都必须在初始化器{}中声明。 但幸运的是,您可以告诉编译器您传递的数组至少在特定持续时间内将是const。 你可以做到以下这会产生

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

内部的const_cast将删除std :: string所拥有的字符数组的常量。 因此,很可能函数可能会改变std :: string后面的字符数组的内容。 当知道采用这种参数的函数的行为时,这可能是正常的。

如果你想创建一个char *的const数组而不使用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]));

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM