-3
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?

shivam mitra
  • 232
  • 1
  • 5
  • 12

3 Answers3

7

p[4] equals 't'. Its ASCII code is 116.

p[1] equals 'r'. Its ASCII code is 114.

Thus p+p[4]-p[1] is p+2, i.e. 2 bytes past where p is pointing: EDIT: Matt's answer brings up a very good point -- pointer arithmetic outside the string is undefined behavior, too, so 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.

Lynn
  • 10,425
  • 43
  • 75
6

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).

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365
  • Are you sure this causes undefined behaviour ? p + p[4] is never deferenced, p[1] is substracted from it before it is passed to printf (does it cause undefined behavior to have an invalid pointer as an intermediate result even if it's not deferenced ?) – BrunoLevy Jul 28 '15 at 14:44
  • 1
    @BrunoLevy Yes. The wording in the standard is "If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.". C11, 6.5.6 This refers to adding an integer to a pointer. – Art Jul 28 '15 at 15:06
1

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

Jon..
  • 430
  • 1
  • 5
  • 16