【发布时间】:2012-03-07 00:50:59
【问题描述】:
是否可以在 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 中初始化结构,它就不起作用。关于如何全局初始化 table1 的任何想法?
【问题讨论】:
-
不要在 C 程序中强制转换
malloc()的返回值。 -
究竟是什么意思?我的意思是如何使用 malloc 而不强制转换我使用的类型?
-
malloc 的返回类型是 void * -- 你不需要强制转换它。只需移除演员表,它就可以正常工作。
-
您没有显示“n”被声明或初始化。这显然不是您的实际代码——它不会编译。因此,我们无法为您的初始化失败的原因提供真正的答案。
-
向我们展示您的
distance()函数的代码;问题可能就在那里。
标签: c struct initialization