2013-12-10 20 views
-1

考慮一個具有動態分配的數組作爲成員的struct,例如:保護const的結構的動態數組構件

struct matrix { 
    unsigned cols; 
    unsigned rows; 
    double* data; 
}; 

如何可以寫像print_matrix(const matrix);,保證數據data點的功能,以不被修改?

能否定義類似

struct const_matrix { 
    const unsigned cols; 
    const unsigned rows; 
    const double* data; 
}; 

,然後隱式轉換struct matrixstruct const_matrix

Here是爲什麼第一個版本不起作用的一個小例子。

+2

'print_matrix(const struct matrix)'不起作用嗎?或者函數需要改變一些'matrix'的元素而不是'data'?(這對打印函數來說很奇怪...... ) – Kninnug

+0

@Kninnug看來這個版本只保護指針'data'的值,而不是它指向的數據。在我試過的一個例子中它仍然被改變。 –

回答

0

是的,你的直覺是正確的。您可以定義struct const_matrix就像你有再投給它:

void print_matrix(struct const_matrix *m) 
{ 
    // This bad implementation tries to change data. 
    // It does not compile. 
    m->data[0] = 100; 
} 

稱呼它,從(結構矩陣*)轉換爲(結構const_matrix *)。例如:

{ 
    struct matrix m; 
    m.cols = 4; 
    m.rows = 4; 
    m.data = calloc(sizeof(double), m.cols*m.rows); 

    ... 

    print_matrix((struct const_matrix *)&m); 
} 

請注意,您必須從(struct matrix *)轉換指針類型(即投地(struct const_matrix *),因爲C不會讓你一個結構轉換爲另一種(即鑄造從(struct matrix)(struct const_matrix)是不允許的)

+0

這個指針保證是保存嗎? (我是一個C++的人,我所聽到的只是「小心C風格的演員」)。 –

+0

是的,只要結構是相同的(除了「consts」)。 consts限定符不會影響成員的大小,對齊或打包。也就是說,您正在做一個權衡:強制執行print_matrix不會造成不良影響,代價是現在需要保持兩個結構同步。 –

0

你可以有另一個const有:

double * const data; // non constant pointer to constant data 

甚至

double const * const data; // constant pointer to constant data 
+1

我不確定這個答案解決了他的問題。 @Malloc試圖創建他的矩陣結構的不可變版本。 –