2016-05-29 57 views
0

我定義瞭如下結構:如何正確初始化其中一個成員是數組的結構?

typedef struct sp_point_t* SPPoint; 

struct sp_point_t 
{ 
    int dim; 
    int index; 
    double* data; 
}; 

然後我想初始化結構的實例:

foo (double* data, int dim, int index) 
{ 
double* dataInserted; 
dataInserted = (double*) calloc(dim,sizeof(double)); 
//inserting values to dataInserted 
SPPoint newPoint = {dim, index, dataInserted}; // warning! 
} 

但是在編譯的時候我得到了一個「標量初始化多餘元素」交戰(在最後一行)。

這個警告是什麼意思?爲什麼我不能用這種方式初始化一個實例?

謝謝

+0

你不需要投上'calloc' - 參見[這裏](http://stackoverflow.com/questions/605845/do- i-cast-malloc的結果) –

+3

歡迎來到Stack Overflow。請儘快閱讀[關於]頁面,以及有關創建MCVE([MCVE])的信息。您尚未顯示「SPPoint」的typedef。它是'typedef struct sp_point_t SPPoint;'或'typedef struct sp_point_t * SPPoint;'或者其他什麼東西?你也沒有顯示局部變量'dim'或'index'。這些遺漏使得無法確定需要採取哪些措施來解決您的問題。我的猜測是你有一個指針(在這種情況下,閱讀[是否是一個好主意typedef指針?](http://stackoverflow.com/questions/750178/))。 –

+0

'data'是一個指針,而不是一個數組 –

回答

1

您正在初始化一個指向struct而不是stuct本身的指針。下面的工作(如果你的意思是在你的代碼結構創建):

foo (double* data, int dim, int index) 
{ 
    double* dataInserted; 
    dataInserted = (double*) calloc(dim,sizeof(double)); 
    //inserting values to dataInserted 
    struct sp_point_t newPoint = {dim, index, dataInserted}; // Corrected code 
}