0

I would like to know why the function scanVector in my program assigns only the first value to the first element of x and not the rest to their respective locations,

#include <stdio.h>
#include <assert.h>

double* scanVector(int length) {
  assert(length > 0);
  double vector[length];
  int j = 0;
  for (j=0; j<length; ++j) {
    vector[j] = 0;
    printf("vector[%d] = ",j);
    scanf("%lf",&vector[j]);
    printf("vector[%d] = %f\n",j,vector[j]);

  }
  return &vector[length];
}

main() {
  double* x;
  int j = 0;
  int dim = 0;

  printf("dim = ");
  scanf("%d",&dim);

  x = scanVector(dim);

  for (j=0; j<dim; ++j) {
    printf("x[%d] = %f\n",j,x[j]);
  }
}

even though the for loop does its job just fine as you can see from the output with input parameter dim = 2:

dim = 2
vector[0] = 1
vector[0] = 1.000000
vector[1] = 2
vector[1] = 2.000000
x[0] = 0.000000
x[1] = 0.000000
JayRyne
  • 3
  • 2
  • The function is returning the address of a local variable. That results in undefined behaviour as local variables cease to exist when the function exits. – kaylum Apr 27 '20 at 07:13
  • Common solutions: The function allocates dynamic memory and returns a pointer to that memory or the caller passes in a pointer to the buffer. – kaylum Apr 27 '20 at 07:14
  • @kaylum thanks, I'm really new to C so I'm not sure, are you suggesting applying call by reference to the function? If so, could you kindly recommend some way? – JayRyne Apr 28 '20 at 06:32

0 Answers0