我在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+1nenter 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"
在哪里?为什么它们被忽略了?
abcdef0???... <- the contents of array (0 means NUL, ? means indeterminate)
ef0? <- what is written to the position (shifted 2 characters)
将str[o+2]
分配给str[o]
本身不会改变str[o+2]
, 但是后来o
会因为for
语句而变得o+2
,然后将str[o+2]
分配给str[o]
意味着将str[o+4]
分配给具有原始o
值的str[o+2]
。
然后,写入终止空字符并结束字符串。