簡體   English   中英

結構的初始化

[英]Initialization of a struct

是否有可能在main之前初始化c中的結構的對象表? 我有這個結構:

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 

}   

因為我想做一個距離函數,我注意到如果我在main初始化struct,它就不起作用。 關於如何初始化全局table1任何想法?

以下是數組全局初始化的示例:

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

但是,您顯示的代碼應該非常相同。

你可以在main之外移動malloc調用,但這應該沒有區別。 只要table1在main之外聲明(在您的示例中),它應該對整個翻譯單元可見。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM