0
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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

2 Answers2

3

There are three concepts involved:

  1. scanf("%d", pointer) method will read the integer value (%d) from stdin and write it to the memory referenced by pointer.
  2. Nature of arrays: arrays in C are stored linearly in memory: int array of size n is just n * sizeof(int) bytes in memory and the variable of the array is the same as the pointer to its first element.
  3. Pointer arithmetic: array + i moves the pointer by i memory cells of type int which is i * sizeof(int) bytes. This is exactly where the i'th element of array is. So array + i is a pointer to array[i].
Dmitrii Abramov
  • 106
  • 1
  • 5
1

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 ).

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335