简体   繁体   中英

Removing charAt from c string

I am trying to write simple removeAt(char* str, int pos) in C, but confused by result.

char c[] = "abcdef";
char* c1 = removeAt(c, 3);

cout << c1;

If I am doing it in this way:

static char* removeAt(char* str, int pos)
{
   int i = 0;

   for(i = pos; str[i] != '\0'; i++)
   {
       str[i] = str[++i];
   }

   str[i] = '\0';

   return str;
}

string stays the same "abcdef";

If I am doing:

static char* removeAt(char* str, int pos)
{
 int i, k =0;

for(i = pos, k = pos;  str[i] != '\0'; i++)
{
   str[i] = str[++k];
}

str[i] = '\0';

return str;
}

does work as intended.

In this loop

for(i = pos; str[i] != '\0'; i++)
{
    str[i] = str[++i];
}

You change the value of i by doing i++ , so you end up missing a character every two, or something similar. Change i++ to i+1 .

EDIT: By the way, the line

str[i] = str[++i] 

is undefined behaviour, since it's not specified when the increment will occur (before or after evaluating the left side?). If the right side is evaluated first then your code would be

i++;
str[i] = str[i];

Effectively doing nothing, as you observe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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