Reputation: 1
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?
Upvotes: 0
Views: 64
Reputation: 1458
A simple way to understand it:
For printf("%s", p + p[2] - p[1]);
, The value of p+p[2]-p[1]
will be calculated.
p
<- holds a number that represents a memory address. (p
is a pointer)p[2]
<- holds a number 67 represent C
.p[1]
<- holds a number 65 represent A
.The expression becomes p+2
,
print("%s", p+2)
means print the string starting from the 3rd char.
Upvotes: 0
Reputation: 103
Good question. This is caused by the type conversion in C.
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.
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.
Upvotes: 1
Reputation: 3774
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"
.
Upvotes: 0