tags:

views:

121

answers:

6
char a[]="HELLO";
char *p="HELLO";

will a[2] and p[2] fetch the same character?

A: 

Both will have the same character value.

jwenting
+2  A: 

What they will fetch is a char-sized chunk of memory located 2 char-sized steps (2 bytes here) after the beginning of each, or after the address in memory to which each var points. This happens to be 'L' i the example, but this is not the same address in memory.

So yes, in the example given, they will fetch the same character.

mingos
are you sure it's not the same memory address? :)
Nick D
Thanks to all..
Dj
@Nick D: it must not be the same memory address. `a` is an array containing a copy of a string literal "HELLO", whereas `p` is a pointer to a string literal "HELLO".
Steve Jessop
Yes.. because they are two different automatic valiables. One is an array and other is a pointer.
Dj
@Steve and @Dj: oh, you're right. Sorry for my misleading comment :-P
Nick D
Well, my answer might also be a tiny bit misleading, actually. What I meant to say is that althought the value returned will be the same *in this example*, the memory address will not, so changing one string won't change the other.
mingos
+1  A: 

Yes.

p[2] is equivalent to *(p+2)

HELLO
  ^
*(p+2)

Should be noted, that the first "HELLO" will probably be stored in a writable memory page, while the second "HELLO" will probably be stored in a read only page. This is very closely related to the compiler / platform you are on.

Tom
A: 

I guess it depends on the compiler you use, but the answer is probably no.

By the way, you can test this easily by comparing the addresses of the two characters. If they differ, then: no.

Anyway, you shouldn't rely on this ;)

ereOn
+1  A: 

In both cases they will fetch an 'L'. However, it isn't the same 'L'. They are stored in different places. That means if you compare their pointers, they will not be equal.

T.E.D.
A: 

Yes It would !!

DeepthiTS