char s[] = "MAC122";
char *p = s;
printf("%s", p p[2] - p[1]);
When I run the C code, the output is "C122", but I don't really understand these and - operations with the elements of the string and can't find any online references. Could anyone help me?
CodePudding user response:
Good question. This is caused by the type conversion in C.
Background: Printing char*
Let's start with a simple example:
printf("%s", p);
This will print all the characters starting from the address p
, i.e. "MAC122".
That's because the string in the memory looks like
And printf
keeps printing characters until it finds '\0', i.e. the terminator.
So what if you do this?
printf("%s", p 2);
This will print out "C122", which is exactly your case.
That means the p p[2] - p[1]
somehow equal to p 2
, right? That's because of the algorithmic operations of between types.
Algorithmic operations between types
First, we know that p[2]
is exactly the character C
, and p[1]
is A
.
What happens if we do the operation 'C' - 'A'
? That results in the conversion from the char
into the ASCII. (It's not really a conversion physically because the computer stores the ASCII value, but logically it helps to understand) Then p[2]-p[1]
equal to 'C'-'A'
equal to 67 - 65
equal to 2
.
Similarly, p p[2] - p[1]
equal to p 67 - 65
equal to p 2
. Using the former knowledge of how printf works, this explains why you get the "C122" output.
CodePudding user response:
The catch lies here: p p[2] - p[1]
. p[2]
is 'C'
, p[1]
is 'A'
. In C, all characters are represented by their ASCII values and 'C' - 'A'
happens to be 2
because 'C'
is the second letter after 'A'
. So, now we have p 2
.
p
is a pointer to a char
and pointer arithmetic dictates that p
be incremented exactly one byte for each increment. Thus, p 2
points to the character 'C'
in the string.
printf
starts from 'C'
and carries on until it finds a '\0'
at the end of the string. Which gives you "C122"
.