c++ - 为什么在 c++ 中分配 char 数组元素时,分配的字符被破坏?
问题描述
我用 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"
?为什么他们会被忽视?
解决方案
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
会o+2
感谢for
语句然后赋值str[o+2]
给str[o]
意味着str[o+4]
用str[o+2]
原始o
值赋值。
然后,写入终止空字符并结束字符串。
推荐阅读
- mongodb - 无法在 mongo db 中使用 $and 获取
- php - Problem with error when I trying filter by relation
- node.js - Node.js 视频流 WEBM Live Feed 到 HTML
- html - Bootstrap 4,我的 navbar-collapse 类中的导航项之一在它处于活动状态时不会改变背景颜色
- javascript - 如何在mongoDB中搜索用户的名字和姓氏并返回完整的对象
- git - 如何识别 git 中两次提交之间的增量更改
- matrix - 如何在 GNU Octave 中比较矩阵
- sql - 优化使用 Laravel Eloquent 构建的查询
- javascript - 如何从 react-bootstrap-typeahead 中的嵌套对象中过滤?
- python - Scrapy:返回空列表