call by reference failure

49 Views Asked by At

I have a task that requires handling a 4X4 matrix that is defined by typedef. the task is to create a calculator for declared matrixes in main and interpret the commands from the user that passed as simple words. the problem is that I trying to pass the matrixes between the function using it address.

int main(){

mat MAT_A,MAT_B,MAT_C,MAT_D,MAT_E,MAT_F; 
printf("MAT_A is at-%p\n",(void*)&MAT_A);
read_command(&MAT_A,&MAT_B,&MAT_C,&MAT_D,&MAT_E,&MAT_F);
}

in this function I interpret the matrixes that are to pass as value to the calculation function str_to_arg pass a mat* as the argument to add_mat function

void read_command(mat *a,mat *b,mat *c,mat *d,mat *e,mat *f){
add_mat((str_to_arg(a,b,c,d,e,f,strtok(NULL,","))),(str_to_arg(a,b,c,d,e,f,strtok(NULL,","))),(str_to_arg(a,b,c,d,e,f,strtok(NULL,","))));
printf("mat added at %p\n",(void*)a);
}

add_mat function receives 3 mat* as arguments

void add_mat(mat *a, mat *b , mat *c){
int i,j;
double sum;
for(i=0 ; i<MAT_LENGTH ; i++){
    for(j=0;j<MAT_LENGTH; j++){
        sum = *a[i][j]+ *b[i][j];
        *c[i][j]=sum;
        
    }
}   

printf("add succeed to matrix at adress %p\n",(void*)*c);
print_mat(*c);
}

as you can see Ive added 3 prints to follow the address at any given time, the addresses of the matrix at main and read_command are the same but the address that in add_mat is different.

I've tried many combinations include passing pointer to pointer and nothing seems to pass the right address into add_mat so the values of the actual matrix are'nt changing.

thanks for your help.

1

There are 1 best solutions below

0
tstanisl On

Dereferencing of a pointer to 2d array should be done with:

(*a)[i][j]

The reason is that indexing operator [] has higher precedence than *.

The add_mat() function should be:

void add_mat(mat *a, mat *b , mat *c){
int i,j;
double sum;
for(i=0 ; i<MAT_LENGTH ; i++){
    for(j=0;j<MAT_LENGTH; j++){
        sum = (*a)[i][j]+ (*b)[i][j];
        (*c)[i][j]=sum;
        
    }
}