0

When I try to get user input for the dynamic array, it stops at the first for loop. It gives me an error that my program has stopped working. Help me out!

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

int main(){
    int count = 0, sum = 0, *number = NULL, index = 0, size = 0;
    scanf("%d", &size);

    number = (int *)calloc(size, sizeof(int)); //Dynamic allocation

    printf("Enter the elements\n");
    for(index = 0; index < size; index++){
        scanf("%d",number[index]); //Getting the input values from user but i get an error
    }
    return 0;
}
Sridhar
  • 21
  • 3
  • `int *number; .... scanf("%d",number[index]);` Save time. Enable compiler warnings, Faster feedback the posting on SO. – chux - Reinstate Monica Dec 14 '19 at 08:16
  • Generally `scanf` is not a good idea. See [what-can-i-use-for-input-conversion-instead-of-scanf](https://stackoverflow.com/questions/58403537/what-can-i-use-for-input-conversion-instead-of-scanf/58405772#58405772) for lots of information on this. Using `fgets` in combination with `sscanf` is already a big improvement. – hko Dec 16 '19 at 17:11

1 Answers1

2

Use this instead:

scanf("%d", &number[index]);

Note the & operator before number[index] is needed when using scanf for integer input.

kiner_shah
  • 3,939
  • 7
  • 23
  • 37