Search code examples
cscanfpointer-arithmetic

What scanf("%d", array + i); does


void get_elemnts(int *array, int max_index){
    for(int i = 0; i < max_index; i++){
        printf("enter element 0%d: ", i);
        scanf("%d", array + i);
    }
}

**scanf("%d", array + i);**Can someone explain? I have a code that gets the elements of an array from the user input. And at the moment I have difficulties with understanding what exactly this part of the code does


Solution

  • This function definition

    void get_elemnts(int *array, int max_index){
        for(int i = 0; i < max_index; i++){
            printf("enter element 0%d: ", i);
            scanf("%d", array + i);
        }
    }
    

    is equivalent to

    void get_elemnts(int *array, int max_index){
        for(int i = 0; i < max_index; i++){
            printf("enter element 0%d: ", i);
            scanf("%d", &array[i] );
        }
    }
    

    This expression array + i gives pointer to the i-th element of the array.

    The format %d used in the function scanf expects a pointer to an object of the type int and this expression array + i yields the pointer using the pointer arithmetic.

    The expression array[i] is equivalent to the expression *( array + i ).

    So the expression &array[i] is the same as &*( array + i ) where the applied operators &* can be omitted and you will get just ( array + i ).