char s[] = "arista2015";
char *p = s;
printf("%s",p+p[4]-p[1]);
This program gives the output as
ista2015
Can somebody explain the output?
char s[] = "arista2015";
char *p = s;
printf("%s",p+p[4]-p[1]);
This program gives the output as
ista2015
Can somebody explain the output?
p[4]
equals 't'
. Its ASCII code is 116.
p[1]
equals 'r'
. Its ASCII code is 114.
Thus EDIT: Matt's answer brings up a very good point -- pointer arithmetic outside the string is undefined behavior, too, so p+p[4]-p[1]
is p+2
, i.e. 2 bytes past where p
is pointing:p+116-114
and p+2
aren't actually guaranteed to be the same thing.
'a' 'r' 'i' 's' 't' 'a' '2' '0' '1' '5' '\0'
^ ^
p p+2
Amusingly, this is undefined behavior, though! On an EBCDIC system, it would print an empty string, as there 't' - 'r' == 10
(yes, really). The C99 standard only guarantees that the codes corresponding to the decimal digits '0'
, '1'
, '2'
... '9'
are consecutive.
Since the additive operators are left-right associative, the crucial expression is:
(p + p[4]) - p[1]
and not p + (p[4] - p[1])
as suggested by other answers/comments. Since p + p[4]
is well outside the bounds of s
, this causes undefined behaviour, which means that anything can happen (including, but not limited to, any particular output).
Try to run these code and study the output
#include<stdio.h>
int main(){
char s[] = "arista2015";
char *p = s;
printf("Address of p: %d\n",p);
printf("Address of 'a' in arista2015 : %d\n",&s[0]);
printf("Address of'r' in arista2015 : %d\n",&s[1]);
p=p+p[4]-p[1]; // Now address of P becomes p + 2 so its points to address of 'i'
printf("Address of 'i....'%d\n",&s[2]);// and it print from address of i before null
printf("%d\n",p);//prints the address
printf("%s\n",p);//prints the value
}
Run These code and check how its working as explain above..
my Output:
Address of p: 2686737
Address of 'a' in arista2015 : 2686737
Address of'r' in arista2015 : 2686738
Address of 'i....'2686739
2686739
ista2015