【问题标题】:Initialization of a struct结构的初始化
【发布时间】: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


【解决方案1】:

以下是数组的全局初始化示例:

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

但是,您所显示的代码应该几乎是等效的。

【讨论】:

  • 是的,我想创建一个对象表,而不仅仅是一个二维表。
  • 我给出的例子就是这样,一个结构数组。
【解决方案2】:

您可以将 malloc 调用移到 main 之外,但这应该没有什么区别。只要 table1 在 main 之外(在您的示例中)声明,它就应该对整个翻译单元可见。

【讨论】:

  • 问题是初始化,而不是表的大小。当我使用距离时,它返回 0 而不是实际值。
  • @FereRes - 你用过调试器吗?这些赋值语句显然是在调用 distance 之前发生的,因此 table1 应该在 distance 函数的执行期间设置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-16
  • 1970-01-01
相关资源
最近更新 更多