Compare the memory access of the following form:
{
char a[] = "vijoeyz";
char *p = "vijoeyz";
putchar ( a[6] );
putchar ( p[6] );
}
Ans Let the base address of the array A to be 4000.
Then, this array looks like this:
___________________________
a: | v | i | j | o | e | y | z |
---------------------------
4000 1 2 3 4 5 6
Let the string literal, pointed by P, reside at 5000.
Like the identifier A, P is also an automatic variable.
So it's address would be 4007 and the content would be
the address(5000) of the string literal. Here is the
picture:
___________________________
| v | i | j | o | e | y | z |
---------------------------
5000 1 2 3 4 5 6
______
p: | 5000 |
------
4007
Now to access a[6], the compiler generates the code as
follows:
* Add base address(4000) and the offset(6)
* Read the byte from the resultant location(4006)
And to access p[6], the compiler generates the code as
follows:
* Read the contents of pointer P (5000)
* Add the offset(6) to the value read from P(5000)
* Read the byte from the resultant location(5006).
If you observe, access using the pointer requires two memory
fetches, whereas that of array requires only one. This shows
that array accesses are faster than that by pointers.