gpt4 book ai didi

C语言: bug = different matrix values when i print it in the main function

转载 作者:行者123 更新时间:2023-11-30 14:50:18 26 4
gpt4 key购买 nike

int main(){

int f,d;
float** a1, **a2,**p,**t;
read_from_file(a1,a2);
/*DEBUG PRINT AGAIN MATRIX A1 */
for(f = 0; f<4; f++)
for(d = 0; d<4; d++)
printf("a[%d][%d] = %f\n",f,d,a1[f][d]);
}


void read_from_file(float** a, float** b){
a = my_malloc(4,4);
b = my_malloc(4,4);
int temp;
FILE* fd;
fd = fopen("matrici.txt","r");
if(fd == NULL){
perror("errore opening file\n");
exit(1);
}
int i,j;
for(i=0; i<4; i++)
for(j=0; j<4; j++){
fscanf(fd,"%d", &temp);
a[i][j]= (float)temp;
}
for(i=0; i<4; i++)
for(j=0; j<4; j++){
fscanf(fd,"%d", &temp);
b[i][j]= (float)temp;
}
fclose(fd);

/* DEBUG PRINT MATRIX "A1" */
for(i = 0; i<4; i++)
for(j = 0; j<4; j++)
printf("a[%d][%d] = %f\n",i,j,a[i][j]);
}

好吧大家好,当我编写一个程序时,该程序必须从文件中读取一些浮点值并将它们存储到该矩阵中,出现了一个常见的错误:当我在“从文件读取”函数中打印矩阵时,存储在其中的值是:

a[0][0] = 3.000000
a[0][1] = 1.000000
a[0][2] = -1.000000
a[0][3] = 0.000000
a[1][0] = 0.000000
a[1][1] = 7.000000
a[1][2] = -3.000000
a[1][3] = 0.000000
a[2][0] = 0.000000
a[2][1] = -3.000000
a[2][2] = 9.000000
a[2][3] = -2.000000
a[3][0] = 0.000000
a[3][1] = 0.000000
a[3][2] = 4.000000
a[3][3] = -10.000000

但是当我在主函数中再次打印相同的矩阵时(在调用 read_from_file 之后),存储在其中的值是:

a[0][0] = 53806348.000000
a[0][1] = 14144784983268524032.000000
a[0][2] = 208613343232.000000
a[0][3] = 15659650322576441344.000000
a[1][0] = 13841544192.000000
a[1][1] = 0.048908
a[1][2] = 71857615689329949954782789632.000000
a[1][3] = 202218044416841482240.000000
a[2][0] = 3664429973504.000000
a[2][1] = 15151608880334635008.000000
a[2][2] = 234149008.000000
a[2][3] = 55906620.000000
a[3][0] = 14358698268987228160.000000
a[3][1] = 3157.142334
a[3][2] = 15151608880334635008.000000
a[3][3] = 13.265934

感谢您的帮助:)

最佳答案

函数的参数是其局部变量。您可以想象按以下方式调用函数 read_from_file 及其定义

float** a1, **a2,**p,**t;
read_from_file(a1,a2);

//...

void read_from_file( /*float** a, float** b */){
float **a = a1;
float **b = a2;

a = my_malloc(4,4);
b = my_malloc(4,4);
//...

因此,在函数内,原始参数 a1b1 不会更改。该函数处理原始参数值的副本。

如果您想在函数内更改参数,则应该通过引用间接通过指针传递参数。

例如

float** a1, **a2,**p,**t;
read_from_file( &a1, &a2 );

//...

void read_from_file( float ***a, float ***b){

*a = my_malloc(4,4);
*b = my_malloc(4,4);
//...

关于C语言: bug = different matrix values when i print it in the main function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49068672/

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