Reputation: 5386
Is there possible to initialize a object-table of a struct in c before main? I've got this struct:
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
}
As I wanna make a distance function I noticed that it doesn't work ifI initialize struct inside main
. Any idea about how can I initialize globally table1
?
Upvotes: 1
Views: 654
Reputation: 4518
You can move the malloc
call outside main, but that should make no difference. As long as table1
is declared outside of main, which it is in your example, it should be visible to the entire translation unit.
Upvotes: 0
Reputation: 225172
Here's an example of a global initialization for your array:
customer table1[] = { { 0, 0, 0 },
{ 0, 12, 1000 },
{ 6, 5, 1500 },
{ 7, 15, 800 } };
However, what you have shown of your code should be pretty much equivalent.
Upvotes: 3