0

我尝试用-0.8到0.8之间的随机数填充一个向量(我必须分配)。我的问题是为什么在我调用函数 setvector() 时在主函数中不返回向量并且我仍然用零初始化?非常感谢。我在这里做了什么

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

void allocate(double **a, int size) {
    *a = malloc(size);
}

double setvector(double *v){
    int i, seed, send_size;

    send_size = 10;

    allocate(&v, send_size * sizeof(double)); // allocate memory for the vector
    seed = time(NULL);
    srand(seed);
    for (i = 0; i < send_size; i++)
    {
        v[i] = 1.6*((double) rand() / (double) RAND_MAX) - 0.8;
    }
    printf("Inside function the vector is:\n\n");
    for (i = 0; i < 10; i++)
    {
        printf("The %d element has the random %4.2f\n", i, v[i]);
    }
    return *v;
}

int main(){
    double *v = NULL;
    setvector(v);
    printf("\nThe vector from main is:\n\n");
    printf("The 1st element of v is %4.2f\n", &v[0]);
    printf("The 1st element of v is %4.2f\n", &v[1]);

    return 0;
}

这是我的屏幕输出:

在函数内部,向量是:

0元素有随机-0.79
1元素有随机-0.34
2元素有随机0.48
3元素有随机-0.67
4元素有随机-0.70
5元素有随机0.61
6元素有随机 -0.67
7 元素具有随机 -0.66
8 元素具有随机 -0.44
9 元素具有随机 -0.36

来自 main 的向量是:

v
的第一个元素是 0.00 v 的第一个元素是 0.00

4

1 回答 1

6

main您将数组元素的地址传递给printf

printf("The 1st element of v is %4.2f\n",&v[0]);
printf("The 1st element of v is %4.2f\n",&v[1]);

那应该是printf(..., v[0]);

更远:

double setvector(double *v){

不会改变vmain所以v保持NULL在那里。你应该setvector接受一个double**, likeallocate并将它的地址传递给它v

于 2013-01-29T18:53:48.657 回答