【发布时间】:2014-10-07 04:48:32
【问题描述】:
在尝试创建 shell 几天后,我请求了一些帮助。我已经开始使用不同的数据结构超过 4 次,并请求解决以下问题。我有一个字符串,我需要将它分解成单独的参数并有一个指向它的指针。我最终将 args 传递给 exec 函数,但由于我似乎无法正确填充 args,我得到了有趣的结果,这是正在发生的事情的简化版本
char* args[100];
int counter=0;
string temp = "some text and stuff here";
stringstream s (temp);
while(s>> temp)
{
cout << "TOKEN " << counter << " =" << temp <<endl;
args[counter]=const_cast<char *> (temp.c_str());
counter++;
}
//print the debug info
for( int ii=0; args[ii] != NULL; ii++ )
{
cout << "Argument OUT " << ii << ": " << args[ii] << endl;
}
这段代码不起作用,我不明白为什么。 结果将“此处”存储在 args 的每个值中,但计数器会发生变化。
TOKEN 0 =some
TOKEN 1 =text
TOKEN 2 =and
TOKEN 3 =stuff
TOKEN 4 =here
Argument OUT 0: here
Argument OUT 1: here
Argument OUT 2: here
Argument OUT 3: here
Argument OUT 4: here
【问题讨论】:
-
c_str 返回一个 const 指针是有原因的!
-
@NeilKirk 常量问题与指向同一个地方的指针无关。请注意,他需要非常量指针,因为这是
exec*()系列函数所需要的,即使它们不修改传递的字符串,所以const_cast在这里是安全的。导致问题的原因是重复使用相同的std::string对象。
标签: c++ string const-cast