我很確定這是一個新手的錯誤,但我無法弄清楚。我試着製作一個迴文檢查器,但每當我嘗試將一個通過的字符數組拆分成一半時,它會在分割字符數組的末尾添加隨機(?)字符。我嘗試了谷歌搜索,但無濟於事。也許它與一個以null結尾的字符串有關,但是char數組的長度表明除了我傳遞的字符以外沒有其他字符。代碼在這裏:分裂字符數組增加(看似)隨機字符
#include <iostream>
bool isPalindrome(char* passedString){
int len = strlen(passedString);
char lh[len/2];
char rh[len/2];
std::cout << "Length is: " << len << std::endl;
if(len % 2 == 0){
for(int i = 0; i < len/2; i++){
lh[i] = passedString[i];
}
int tmpCount = 0;
for(int i = len/2; i < len; i++){
rh[tmpCount] = passedString[i];
tmpCount++;
}
}
std::cout << "Left half: " << lh << std::endl << "Right half: " << rh << std::endl;
return 0;
}
int main(){
isPalindrome("test");
return 0;
}
返回此輸出編譯和執行後:
Length is: 4
Left half: te�Y�
Right half: st�Y�
'炭LH [len個/ 2]':運行時大小的數組是C99功能不可C++。使用'std :: string'來避免這種問題。 – 101010