Search code examples
arrayscinitializationscanfdeclaration

i get some problems with scanf() in C


#include <stdio.h>
#include <stdlib.h>

void add(int *arr, int n);

int main() {
  int arr[] = {};
  add(arr, 4);

  return 0;
}

void add(int *arr, int n){
  for (int i = 0; i < n; i++){
    printf("%d index is : ", i);
    scanf("%d\n", &arr[i+1]);
  }
}

the for loop doesn't work after the i == 1... the execution stops and then I have to press some alphabet and executes the whole for loop with no values...


Solution

  • This declaration in C and in C++

    int arr[] = {};
    

    is invalid. The initializer list shall not be empty.

    Instead you could write in C

    int arr[4] = { 0 };
    

    or

    int arr[] = { [3] = 0 };
    

    And within the function instead of

    scanf("%d\n", &arr[i+1]);
                       ^^^
    

    you have to write

    scanf("%d", &arr[i]);
                      ^^^
    

    Otherwise there will be an access to memory outside the array.