Help with char array n char pointer

IndiraP's Avatar, Join Date: Nov 2012
Go4Expert Member
#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???
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
What are p[3] and p[1]?
IndiraP's Avatar, Join Date: Nov 2012
Go4Expert Member
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..
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
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.
IndiraP's Avatar, Join Date: Nov 2012
Go4Expert Member
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..
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
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
IndiraP's Avatar, Join Date: Nov 2012
Go4Expert Member
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...