Can someone explain to me how this works?
it doesn't work, the behavior of the program is undefined. Nothing meaningful can be said about the outcome (even if it looks correct in some specific case).
For example, here on godbolt the output is not brcdbr
but brcdrr
.
That's because it's illegal to invoke strcpy
with overlapping source and destination pointers:
C11 §7.24.2.3 The strcpy function
The strcpy function copies the string pointed to by s2 (including the
terminating null character) into the array pointed to by s1. If
copying takes place between objects that overlap, the behavior is
undefined.
(note: C++ inherits C rules for C standard library functions)
Anyway, if you just wanted to know the intention behind strcpy(s+i, s+i+1)
, in C++ expressions an array automatically decays to a pointer. So char s[12]
becomes char* s
. Then the expression s+i
becomes pointer arithmetic - taking an address of i
th element pointed-to by s
. It is equivalent to writing &s[i]
, i.e. taking an address of i
th element in s
. The same applies to s+i+1
- it evaluates to a pointer to the i+1
th element in s
. The intention of the strcpy
call was to copy the remainder of the string after a
to the memory are starting at a
, i.e. to shift the remaining characters forward by one, thus overwriting the a
.
A better way in C++ would be to use std::string
and the erase-remove idiom to remove the characters a
from the string:
#include <iostream>
#include <algorithm>
#include <string>
int main() {
std::string s = "abracadabra";
s.erase(std::remove(s.begin(), s.end(), 'a'), s.end());
std::cout << s << std::endl;
}
Prints:
brcdbr