Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Help with char array n char pointer (http://www.go4expert.com/forums/help-char-array-n-char-pointer-t29286/)

IndiraP 10Nov2012 22:08

Help with char array n char pointer
 
#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 11Nov2012 05:24

Re: Help with char array n char pointer
 
What are p[3] and p[1]?

IndiraP 11Nov2012 11:20

Re: Help with char array n char pointer
 
Quote:

Originally Posted by xpi0t0s (Post 98188)
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 11Nov2012 14:42

Re: Help with char array n char pointer
 
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 11Nov2012 19:46

Re: Help with char array n char pointer
 
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 13Nov2012 04:50

Re: Help with char array n char pointer
 
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 13Nov2012 10:57

Re: Help with char array n char pointer
 
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..:D
Thank U Sir... :)


All times are GMT +5.5. The time now is 18:21.