Following code deletes the 7th character and beyond from string I figured this out but can anyone clarify me the general logic of an array and operations like S1[6] -= S1[6];
. I searched array arithmetic but it relates with address arithmetic and pointers. Thanks for the help.
#include <string.h>
int main()
{
char S1[]= "Hello World";
S1[6] -= S1[6];
printf("%s",S1);
}
S1[6] -= S1[6];
is equal to
S1[6] = S1[6] - S1[6];
which is also equivalent to
S1[6] = 0;
or better in the context
S1[6] = '\0';
S1[6]
, the 7
th element of array S1
with the value of the 'W'
character is subtracted by itself and the result, actually 0
, is assigned back to the 7
th array element.
It makes the 7
th element of the string a null character, which terminates the string, although all characters which come after the 7
th element aren´t overwritten/erased.
This has the effect, that the output of your program will be "Hello "
instead of "Hello World"
.