c语言:bug =我在主函数中打印时的不同矩阵值[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

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

但是当我在main函数中再次打印相同的矩阵时(在调用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

谢谢您的帮助 :)

c arrays matrix
1个回答
1
投票

函数的参数是它的局部变量。您可以通过以下方式想象调用函数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);
    //...
© www.soinside.com 2019 - 2024. All rights reserved.