Home > Software engineering >  Why does my array prints only the first element?
Why does my array prints only the first element?

Time:12-09

    double fun(int size) {

    double *arr = (double*)calloc(size, sizeof(double));
    assert(arr);
    for (int i = 0; i < size; i  ) {
        scanf_s("%lf", &arr[i]);
    }
    return *arr;
    
    
}
void main() {
    int size = 5;
    printf("%lf", fun(size));
}

trying to print my array using the main function, it prints only the 1st element from the array.. someone have an idea how to fix it?

CodePudding user response:

double fun(int size)

Consider what the function is returning. A single double. The line *arr will get the value of the first element in the arr pointer and return it. What I think you mean to do is iterate over each element in a pointer to a double returned by the function.

double *fun(int size) {

  double *arr = (double*)calloc(size, sizeof(double));
  assert(arr);
  for (int i = 0; i < size; i  ) {
    scanf_s("%lf", &arr[i]);
  }
  return arr;
}
void main() {
  int size = 5;
  double *arr = fun(size);
  for (int i = 0; i < size; i  ) {
    printf("%lf", arr[i]);
  }
}
  • Related