Nick Keighley
9/8/2011 9:44:00 AM
On Sep 8, 1:39 am, Stanley Rice <hecong...@gmail.com> wrote:
> I am confused of the underlying implementation of array indexing and
> pointer arithmetic.
>
> In comp.lang.c FAQ list · Question 6.3, it states that
> ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
> A reference to an object of type array-of-T which appears in an
> expression decays (with three exceptions) into a pointer to its first
> element; the type of the resultant pointer is pointer-to-T.
> That is, whenever an array appears in an expression, the compiler
> implicitly generates a pointer to the array's first element, just as
> if the programmer had written &a[0]. (The exceptions are when the
> array is the operand of a sizeof or & operator, or is a string literal
> initializer for a character array. [footnote] See questions 6.23,
> 6.12, and 1.32, respectively.)
>
> As a consequence of this definition, and in spite of the fact that the
> underlying arrays and pointers are quite different, the compiler
> doesn't apply the array subscripting operator [] that differently to
> arrays and pointers, after all.[footnote] Given an array a and pointer
> p, an expression of the form a[i] causes the array to decay into a
> pointer, following the rule above, and then to be subscripted just as
> would be a pointer variable in the expression p[i].
> ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
>
> Following the above roles, I suppose that using pointer is more
> efficient(compile efficiency) than using array. To prove my opinion, I
> wrote some code:
>
> --------test.c-------
> #include <stdio.h>
> int main() {
> const char p[] = "hello"; // (1)
> //const char *p = "hello"; // (2)
>
> //Either printf("%d\n", *(p + 2)); is ok, the resulting time
> consumption is almost the same.
> printf("%c\n", p[2]);
> printf("%c\n", p[2]);
> .......//repeat the above statement for 70,000 times.
> return 0;
>
> }
>
> In my ubuntu, I use "time gcc test.c", it nearly takes me 20 seconds
> to compile it.
sounds rather a long time
> But when I comment the (1) statement, uncomment the (2) statement,
> guess what happens? Will it take fewer time than the previous test as
> it is using pointers. However, it takes nearly 25-27 seconds.
>
> Will array first decay to a pointer to the first element of the array
> when the array is referenced in an expression? But, why it looks more
> efficient than using pointer directly?