Search code examples
cpointer-arithmetic

Is the use of (arr+2)[0] right?


I am a student who will be a freshman in an university after this summer vacation.I want to learn about computer programing in advance but I run into some problems. Why when I run the program in devc++,the result is -1 and 44? When I read the book called Pointers On C,In the chapter on functions,the book says that the name of array is a pointer,and in C language arr[m]=*(arr+m),and arr[0] is composed by a pointer and a [number],so can I come to a conclusion that (arr+2),which is a pointer,and[0],can compose (arr+2)[0] equaling to *(arr+2+0)?

int main(void)
{
    int arr[10];
    for(int i=0;i<10;i++)
    {
        arr[i]=i+1;
    }
    int b=*(arr+1);
    int c=(arr+2)[0];//Is this true?
    printf("%d\n",b);
    printf("%d",c);
    return 0;
}

Solution

  • Is the use of (arr+2)[0] right?

    Linguistically yes. But very questionable practice.

    The beautiful invention of C is pointer arithmetic and that is exemplified by the definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))).

    So by definition (arr+2)[0] is the same as (*((arr+2)+(0))) and simplifies to *(arr+2) and arr[2] simplifies to the same thing.

    Array subscripting in C is syntactic sugar on pointer arithmetic. The term 'syntatic sugar' is sometimes overused. But in this case it really is just syntactic sugar.

    The example demonstrates a critically important fact about how C manages arrays. Pointer arithmetic works in units of the type (measured in bytes they occupy) and array subscripting the same. So adding to a pointer (arr+2) and subscripting into an array (arr[2]) have a fundamental relationship.

    When you understand that and realise the that array subscripts start at 0 because of that because they're offsets you get "C" as a language.

    Please never write code like that. Writing code like 7[A] gets funny looks.