Reputation: 3177
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.
Upvotes: 0
Views: 907
Reputation: 2654
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.
Upvotes: 3