简体   繁体   中英

Passing a pointer to a struct to a function in C

I am trying to write a function that adds two matrices by passing in three matrices, the two to be added and the the resulting matrix. I am representing a matrix with a struct. Here is my code

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

typedef struct{
  int rows;
  int columns;
  double *data;
}Mat;

int Add(Mat *m1, Mat *m2, Mat **result);

int main(){
  Mat m1,m2;
  Mat *result = NULL;

  m1.rows=2;
  m1.columns=2;
  double temp1[2][2] = {{1,2},{3,4}};
  m1.data = &temp1[0][0];

  m2.rows = 2;
  m2.columns = 2;
  double temp2[2][2] = {{1,1},{1,1}};
  m2.data = &temp2[0][0];

  Add(&m1,&m2,&result);
  int ii,jj;
  printf("\nresult\n");
  for(ii=0;ii<2;ii++){
     for(jj=0;jj<2;jj++){
         printf("%f ",*result->data++);
      }
    printf("\n");
   }
   printf("%d\n ",result->columns);

 return 0;
}


int Add(Mat *m1, Mat *m2, Mat **result)
{
  int ii,jj;
  double new[m1->rows][m1->columns];
  int mat_size = (m1->rows)*(m1->columns);
  Mat *temp = malloc(sizeof(int)*2+sizeof(double)*mat_size);
  temp->rows = 2;
  temp->columns = 2;

  for(ii=0;ii<(m1->rows);ii++){
    for(jj=0; jj<(m1->columns);jj++){
      new[ii][jj] = *(m1->data++) + *(m2->data++);
     }
  }
  temp->data = &new[0][0];
   *result = temp;

}

The problem I am having is at the end of my main function when I try to print the resulting matrix. It just prints 0s. I am able to print "result"'s columns and rows correctly but not the data. Can anyone help? Thanks in advance

There are several fundamental errors in your Add function. Here a corrected version.

void Add(Mat *m1, Mat *m2, Mat **result)
{
   int ii,jj;
   int mat_size = (m1->rows)*(m1->columns);
   Mat *temp = malloc(sizeof(Mat));         /* Allocate the matrix header */
   temp->rows    = m1->rows;
   temp->columns = m1->columns;
   temp->data    = calloc(mat_size, sizeof(double));     /* Allocate the matrix data */

   for(ii=0; ii<m1->rows; ii++) {
     int row = ii*m1->columns;
     for(jj=0; jj<m1->columns; jj++)
       temp->data[row + jj] = m1->data[row + jj] + m2->data[row + jj]; 
       /* or something like that*/
   }
       /* In any case, incrementing the data pointer is wrong */

  *result = temp;
}

There are still things missing though. There's no sanity check, ie if the matrix dimension are compatible and there are no checks for allocation errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM