2013-03-27 31 views
0

我正在尝试编写一个函数,通过在三个矩阵中传递两个矩阵,添加两个矩阵并生成矩阵,从而添加两个矩阵。我代表一个结构矩阵。这是我的代码将指针传递给C中的某个函数

#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; 

} 

我遇到的问题是在我的主要功能结束时,当我尝试打印生成的矩阵。它只打印0。我能够正确打印“结果”的列和行,但不能打印数据。谁能帮忙?在此先感谢

回答

0

您的添加功能中有几个基本错误。这里是一个更正版本。

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; 
} 

还有事,虽然失踪。没有理智检查,即矩阵维度是否兼容,并且没有检查分配错误。

+0

'data'是一个'double *'不是数组指针或指针指针,所以你不能做两个索引。您需要使用...' - > data [ii * m1-> columns + jj]'来代替。 – 2013-03-27 21:09:31

+0

确实。我会修好它。 – 2013-03-28 07:22:17

+0

谢谢你的帮助。我现在将添加行和列检查。我只是想让指针的第一个工作,因为这对我来说很难。 – Elena 2013-03-28 12:46:31