Help with char array n char pointer

Go4Expert Member
10Nov2012,22:08   #1
IndiraP's Avatar
#include<stdio.h>
void main()
{
char a[]="Gate2011";
char *p=a;
printf("%s", p + p[3] - p[1]);
}

Outputs 2011
Can somebody me the explanation of how it is???
Mentor
11Nov2012,05:24   #2
xpi0t0s's Avatar
What are p[3] and p[1]?
Go4Expert Member
11Nov2012,11:20   #3
IndiraP's Avatar
Quote:
Originally Posted by xpi0t0s View Post
What are p[3] and p[1]?

I think pointer accessing array elements.. i dont know when i run that code i got output 2011...
if u can understand how it works..do explain me..
Mentor
11Nov2012,14:42   #4
xpi0t0s's Avatar
Sorry, let me clarify. In order to work out what is going on, you need to evaluate the expression p+p[3]-p[1]. And as the output is "2011" that means you need to work out why the expression evaluates to &p[4].

My question did not indicate I do not know the answer. I know exactly why it does what it does. The point is to help YOU figure it out.

So have a look at p, work out what it is and what it points at, then if you need to, read the book on character strings again, then you should be able to work out what p[0], p[1], p[2] and so on are.
Go4Expert Member
11Nov2012,19:46   #5
IndiraP's Avatar
I am extremely sorry sir..i never meant that u donot know it..
Thank u for guiding me..
n p indicates the starting position here means it points to 'G'
p[3] means it points to 4th position from 'G' means its 'e'
p[1] means it points to 1st position means its 'a'..
Individually i can get through here...but the arithmetics r what i am not reachable..
help me sir..
Mentor
13Nov2012,04:50   #6
xpi0t0s's Avatar
OK, so do you know that 'a' is in fact an integer constant?
Find its value, and find the value of 'e', you will be able to work out what p+'e'-'a' is.
IndiraP like this
Go4Expert Member
13Nov2012,10:57   #7
IndiraP's Avatar
Okay...!!!
So... 'e'-'a'=101-97=4
And since p is a pointer, p+4 indicates the control to jump to p[4]...and thats where 2 resides..and since %s is mentioned, everything from 2 will be printed...rite..??
and so the 2011....
Yeah...I got it..
Thank U Sir...