简体   繁体   English

在C中将指向结构的指针传递给函数

[英]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. 它只打印0。 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. 没有健全性检查,即矩阵维是否兼容且没有分配错误检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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