2013-04-12 195 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])); 

希望這會有所幫助。