【发布时间】:2019-12-13 16:37:58
【问题描述】:
我用 C++ 编写了一个函数,它从 char 数组中删除两个字符。我认为当我将str[o+2] 分配给str[o] 时,不应更改str[o+2]。但是当我使用 cout 打印它时,我看到 str[o+2] 被更改为 null。
#include<iostream>
#include<string.h>
using namespace std;
void shiftLeft(char*,int, int);
int main(){
char str[100];
cout<<"enter the string: ";
cin>>str;
cout<<"removes the letter with index i and i+1\nenter i:";
int i;
cin>>i;
int n=strlen(str);
shiftLeft(str,i,n);
cout<<str;
return 0;
}
void shiftLeft(char*str,int i, int n){
for(int o=i-1; o<n; o++){
str[o]=str[o+2];
}
}
例如输入 "abcdef" 和 i=3,我希望输出 "abefef" 但我得到 "abef"。最后一个"ef" 在哪里?为什么会被忽略?
【问题讨论】:
-
如果字符串末尾有一个空字符,你要确保它不会被复制。
-
先自己调试试试,这确实是一个很简单的问题。一张纸和一支铅笔在这里最有帮助。还请再次阅读初学者 C 教科书中处理字符串的章节。
-
这也是未定义的行为。在条件
o < n下,变量o最多获得n-1,访问str[o+2]然后等于str[n+1],这是超出范围的。