Link to home
Start Free TrialLog in
Avatar of hemanexp
hemanexp

asked on

Character array..........

Hi,
 
  When i compiled the following program, I got "9" as output. I couldnt able to understand the line "p=(buf+1)[5]".  What this line does?

 main()
{
  char *p;
  char buf[10] ={ 1,2,3,4,5,6,9,8};
  p = (buf+1)[5];
  printf("%d" , p);
}

Thanx.
Avatar of Sys_Prog
Sys_Prog
Flag of India image

buf gives you the base address of array. i.e. address of first elemnet, in your case address of 1.

Now (buf + 1) would give you address of 2nd location i.e. 2

And then (buf+1)[5] means 6th location from (buf+1)

And u are assigning the value at (buf+1)[5] to p

Thus output
ASKER CERTIFIED SOLUTION
Avatar of dennis_george
dennis_george
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Ajar
Ajar

char *p;
char buf[10] ={ 1,2,3,4,5,6,9,8};

//buf[0]    buf[1]      buf[2]      buf[3]     buf[4]   buf[5]  buf[6]    buf[7]  .....
//SAME AS
//buf+0    buf+1      buf+2        buf+3     buf+4    buf+5  buf+6    buf+7  .....
//1          2             3              4            5           6         9         8


//so       (buf+1)[5]  =                                                  VVV
//            pos0        pos1        pos2       pos3      pos4    pos5    pos6

//which is  9
 
hi!

The name of ur array i.e. currently buf, always point to the start of array (logical address) and as u might know that arrays are consecutie memory location.
So if we say that buf is pointing to memory area 1245 (buf -> 1245 ) then there are 10 locations reserved for it (as the space specified was 10) from location 1245 to 1254.

buf[0] -> 1  (memory location 1245)
buf[1] -> 2  (memory location 1246)
   .
   .
   .
buf[9] -> 8  (memory location 1254)


When u write buf[5] it is equivalent that u are pointing five positions ahead from the start of array i.e 1249.
More over (buf+1) is equivalent to buf[1] so wat (buf+1)[5] eventually means fifth location starting from the first location (1246)of array buf. i.e 6th location (1250). thus giving u the value 9.

hope it helps.
regards
fa
If you got your problem solved then please close this question.....

Dennis