首页 > 解决方案 > 为什么在 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"?为什么他们会被忽视?

标签: c++arraysstring

解决方案


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],但是后来oo+2感谢for语句然后赋值str[o+2]str[o]意味着str[o+4]str[o+2]原始o值赋值。

然后,写入终止空字符并结束字符串。


推荐阅读