C ++ const char * to const char * const [英] C++ const char* To const char* const
问题描述
我目前正在为我的类写一个任务,它应该是一个非常基本的shell。我几乎完成,但我遇到一个问题与 execvp
和我的字符数组的参数。这是我的代码的一个轻的代码片段。
I am currently writing an assignment for my class that is supposed to act as a very basic shell. I am nearly finished, but I am running into an issue with execvp
and my character array of parameters. Here is a light snippet of my code.
//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 * / code>到
const char * const
。我读了一些关于 const_cast
的东西,但我不知道这是不是我需要做的。
I understand that the problem is that my character array isn't full of constant data, so I need to essentially go from const char*
to const char* const
. I read something about const_cast
, but I wasn't sure if that is what I need to be doing.
如果你会这么善良,你能帮我得到我的字符数组的数组被这个函数正确接受吗?
If you would be so kind, could you help me get my array of character arrays to be properly accepted by that function? If you need me to post more of my code, let me know.
感谢
推荐答案
问题是你不能将const变量传递给期望非const参数的函数。
The problem is you cannot pass const variable to function expecting non-const argument.
其他单词, const char * / code>是
char *
的子集。
删除 const
/*const*/ char* cmd_left[v.size()+1];
添加 const_cast
此处
cmd_left[i] = const_cast<char *>( v.at(i).c_str() );
您的代码的其他部分看起来可疑,但这将使其编译
other parts of your code look suspicious, but this will make it compile
这篇关于C ++ const char * to const char * const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!