具有动态维度的向量不是来自辅助函数的 scanf()

Vector with dynamic dimension not being scanf() properly from a secondary function

在下面的代码中,我尝试使用辅助函数 scanf() 具有动态维度(由用户输入)的向量。我没有收到任何错误或警告,但矢量没有从 main() 打印出来。关于我所缺少的任何想法?谢谢!

#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]);
   }
}

如您所知,当您希望对函数参数中传递的变量进行永久更改时,您需要传递指向它的指针。

在这种情况下,您想更改一个指针,因此您需要将一个指针传递给该指针。

我会建议一种更简单的方法,即 return 指针而不是通过参数传递它:

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
}

如果你真的想使用双指针,你可以使用这样的东西:

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]);
    }
}