1
#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...

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 2
    `arr` can contain zero elements. You can't "add" anything to it. – Eugene Sh. Jul 07 '22 at 20:42
  • 3
    Please see [What is the effect of trailing white space in a scanf() format string?](https://stackoverflow.com/questions/19499060/what-is-the-effect-of-trailing-white-space-in-a-scanf-format-string) Every character in the format string has a purpose. `scanf("%d\n", &arr[i+1]);` ==> `scanf("%d", &arr[i]);`. Note the index was off-by-one too. – Weather Vane Jul 07 '22 at 20:45
  • thanks for informing me broo... i solved the problem as "\n" was making my FOR LOOP freeze... :) – Aditya Paluskar Jul 07 '22 at 20:51
  • `scanf` is not suitable to parse arbitrary user input. But if you choose to use it, *always* check the return value. – Cheatah Jul 08 '22 at 03:14

1 Answers1

0

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • So many problems in so little code. It also ought to be checking that `scanf()` returns `1`, indicating that it got a number, and dealing with error situations. – Jonathan Leffler Jul 07 '22 at 21:30