gpt4 book ai didi

在函数中更改数组不会更改它在 main 中的值

转载 作者:太空宇宙 更新时间:2023-11-04 05:42:33 25 4
gpt4 key购买 nike

我尝试用介于 -0.8 和 0.8 之间的随机数填充一个 vector (我必须分配)。我的问题是为什么在主函数中当我调用函数 setvector() 时不返回 vector 并且我仍然使用零初始化?多谢。这是我所做的

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

这是我的屏幕输出:

Inside function the vector is:

The 0 element has the random -0.79
The 1 element has the random -0.34
The 2 element has the random 0.48
The 3 element has the random -0.67
The 4 element has the random -0.70
The 5 element has the random 0.61
The 6 element has the random -0.67
The 7 element has the random -0.66
The 8 element has the random -0.44
The 9 element has the random -0.36

The vector from main is:

The 1st element of v is 0.00
The 1st element of v is 0.00

最佳答案

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){

不会改变 main 中的 v,所以 v 在那里保持 NULL。您应该让 setvector 获取一个 double**,例如 allocate,并将 v 的地址传递给它。

关于在函数中更改数组不会更改它在 main 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14590061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com