edited by
660 views
1 votes
1 votes

Explain the Output of the Following C Code:

 

int main()
{
char s[]={'g','a','t','e','c','s'};
char r[]={'G','A','T','E','C','S'};
char *p,*q,*str1,*str2;
p=&s[4];
q=&r[2];
str1=r;
str2=s;
printf("%d",++*p-++*str1++ + ++*str2++-32);
printf("%c",3[s]+++*(s+2)-2[r]+++*q-++*r-32);
return 0;
}

 

edited by

1 Answer

0 votes
0 votes
Short Answer: 100q

Explaination:

1. Pointer 'p' points to address of s[4] = *(s+4) = *(4+s) = 4[s] {This relation between arrays and pointer is important}.

2. Pointer 'q' points to r[2].

3. Pointer str1 points to r[0]

4. Pointer str2 points to s[0]

 

So now we evaluate simply:

1. ++*p = ++(s[4]) = ++('c') = 'd' = 100.

2. ++*str1++ = ++(r[0])++ = ++('G')++ =' H'++ [ ASCII numerical value of 'H' will be taken in this step because pre-increment operator is used which first assigns the values and then increments ] = 72. Notice that after this step, 'H' would be turned to 'I' for next printf calculation.

3. ++*str2++ = 104 [and the array value changes to 'i' after assignment].

So, 100 - 72 + 104 -32 = 100. Since format specifier is %d, hence 100 will be printed.

 

4. For next printf, new array values are:

s[ ] = { 'i', 'a', 't', 'e', 'd', 's' }

r[ ] = { 'I', 'A', 'T', 'E', 'C', 'S' }

Now as mentioned earlier; 3[s] = *(3+s) = *(s+3) = s[3]. So applying the concepts, we get 113 after calculation. This for the case of %c results in q.

Since there is no newline charactor, output will be 100q
edited by

Related questions

2 votes
2 votes
1 answer
3
0 votes
0 votes
1 answer
4
Psnjit asked Jan 12, 2019
1,157 views
main(){unsigned int i= 255;char *p= &i;int j= *p;printf("%d\n", j);unsigned int k= *p;printf("%d", k);} Both the outputs are -1. I have even tried with - int i = 255(3rd ...