2013-03-27 84 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