0

In the below code I am trying to scanf() a vector with dynamic dimension (entered by the user) using a secondary function. I am not getting any errors or warnings, but the vector is not getting printed from main(). Any ideas on what I am missing? Thank you!

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

void save_vector(int dim, float *u);

int main()
{
float *v = 0;
int i, dim;

setlocale(LC_CTYPE, "spanish");

printf("Please enter the vector dimension:\n");
scanf("%d", &dim);

save_vector(dim, v);

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

return 0;
}

void save_vector(int dim, float *u)
{
int i;
u = (float *)calloc(dim, sizeof(float));

for (i = 0; i < dim; ++i)
   {
      scanf("%f", &u[i]);
   }
}
Henry
  • 697
  • 1
  • 6
  • 16

1 Answers1

-1

As you know when you want to make the changes permanent to a variable passed in a function argument you need to pass a pointer to it.

In this case you want to change a pointer so you need to pass a pointer to that pointer.

I would suggest a simpler approach which is to return the pointer instead of passing it by argument:

Live demo

int main() 
{
    float *v;
    int dim;

    printf("Please enter the vector dimension:\n");
    scanf("%d", &dim);

    v = save_vector(dim); // assign the variable allocated in the function

    for (int i = 0; i < dim; ++i)
    {
        printf("%f\n", v[i]);
    }

    return 0;
}

float* save_vector(int dim) //pointer to float return type
{
    int i;
    float *u;
    u = calloc(dim, sizeof *u);

    if(u == NULL) {
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < dim; ++i)
    {
        scanf("%f", &u[i]);
    }
    return u; //return allocated array
}

If you really want to use a double pointer you can use something like this:

Live demo

int main() {

    float *v;
    int dim;

    printf("Please enter the vector dimension:\n");
    scanf("%d", &dim);
    alloc_vector(dim, &v); //allocate vector
    save_vector(v, dim);   //having enough memory assing the values
    print_vector(v, dim);  //print the vector

    return EXIT_SUCCESS;
}

void alloc_vector(int dim, float **u) { //double pointer argument

    *u = calloc(dim, sizeof **u)); //allocate memory for the array
    if(*u == NULL) { //allocation error check
        exit(EXIT_FAILURE);
    }
}

void save_vector(float *u, int dim) {

    for (int i = 0; i < dim; ++i) {
        scanf("%f", &u[i]);
    }
}

void print_vector(float *u, int dim){

    for (int i = 0; i < dim; ++i)
    {
        printf("%f\n", u[i]);
    }
}
anastaciu
  • 23,467
  • 7
  • 28
  • 53