简体   繁体   English

为什么在c ++中分配char数组元素时,分配的字符会被破坏?

[英]Why in assigning a char array elements in c++, the assigned character is destroyed?

I wrote a function in C++ which removes two characters from a char array.我用 C++ 编写了一个函数,它从 char 数组中删除两个字符。 I think when I assign str[o+2] to str[o] , the str[o+2] shoud not be changed.我认为当我将str[o+2]分配给str[o] ,不应更改str[o+2] But when I use cout to print it, I see that str[o+2] is altered with null.但是当我使用 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];
    }
}

For example with input "abcdef" and i=3 , I expect output "abefef" but I get "abef" .例如,输入"abcdef"i=3 ,我期望输出"abefef"但我得到"abef" where are the last "ef" ?最后一个"ef"哪里? Why are they ignored?他们为什么被忽视?

abcdef0???... <- the contents of array (0 means NUL, ? means indeterminate)
  ef0?        <- what is written to the position (shifted 2 characters)

Assigning str[o+2] to str[o] itself won't change str[o+2] , but later o will come to o+2 thanks to the for statement and then assigning str[o+2] to str[o] means assigning str[o+4] to str[o+2] with original o value.str[o+2]分配给str[o]本身不会改变str[o+2] ,但由于for语句,稍后o将变为o+2 ,然后将str[o+2]分配给str[o]表示将str[o+4]分配给具有原始o值的str[o+2]

Then, terminating null character is written and the string ends.然后,写入终止空字符并结束字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM