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