2012-03-07 109 views
1

是否有可能在main之前初始化c中一個結構的對象表?當我想打一個距離函數我注意到,這是行不通的IFI初始化內部main結構結構的初始化

typedef struct customer{ 
    int x, y;// coordinates 
    int quantity; 

} customer; 

customer *table1; 

int main(){ 

    table1 = (customer *)malloc(n * sizeof(customer)); 

    table1[0].quantity = 0; table1[0].x = 0; table1[0].y = 0; //afetiria 
    table1[1].quantity = 1000; table1[1].x = 0; table1[1].y = 12; // 1st 
    table1[2].quantity = 1500; table1[2].x = 6; table1[2].y = 5; // 2nd 
    table1[3].quantity = 800; table1[3].x = 7; table1[3].y = 15; // 3rd 

    distance(1,2) //calculate the distance bet 1st and 2d object 

} 

:我有這個結構。任何關於如何初始化全局的想法table1

+3

不要在C程序中投射'malloc()'的返回值。 – 2012-03-07 00:55:24

+0

究竟是什麼意思?我的意思是我如何使用malloc而不用強制轉換我使用的類型? – 2012-03-07 01:00:32

+0

malloc的返回類型是void * - 你不需要施放它。只要刪除演員,它會正常工作。 – Perry 2012-03-07 01:07:31

回答

3

這裏是爲您的陣列中的全局初始化的例子:

customer table1[] = { { 0, 0, 0 }, 
         { 0, 12, 1000 }, 
         { 6, 5, 1500 }, 
         { 7, 15, 800 } }; 

不過,你已經證明你的代碼應該是幾乎等同的。

+0

是的,我想創建一個不僅僅是一個2D表的對象表。 – 2012-03-07 01:02:44

+2

我給出的例子就是一個結構數組。 – 2012-03-07 01:09:24

0

您可以將malloc呼叫移到main之外,但這應該沒有區別。只要table1在您的示例中聲明在main之外,它應該對整個翻譯單元可見。

+0

問題是初始化,而不是表的大小。當我使用距離時,它返回0而不是實際值。 – 2012-03-07 01:01:47

+2

@ FereRes - 你有過調試器嗎?這些賦值語句清楚地發生在距離調用之前,所以應在執行距離函數期間設置table1。 – prelic 2012-03-07 01:07:10