对C typedef结构的一般误解,以及与指针的关系

时间:2013-06-22 19:56:43

标签: c pointers gcc struct typedef

我认为我对如何在C中声明结构和typedef非常困惑。我一直在阅读 - 根据this回答,我正在做的应该是正确的。我正在尝试声明一个简单的类型(本质上只是一个向量),并将它与指针一起使用,但是有些东西是非常错误的,我不断得到错误(包括其他编译器输出,包括命令):

gcc main.c -o simulator -lm -Wall -std=c99
main.c: In function ‘main’:
main.c:20:3: error: incompatible type for argument 1 of ‘init_agent’
   init_agent(agent_list[i]);
   ^
main.c:9:6: note: expected ‘struct agent *’ but argument is of type ‘agent’
 void init_agent(agent *a)
      ^
make: *** [main] Error 1
[Finished in 0.0s with exit code 2]

我的代码如下:

#include <stdlib.h>

typedef struct agent_s
{
    float x;
    float y;
}agent;

void init_agent(agent *a)
{
    a->x = (float)(rand()%100)/10;
    a->y = (float)(rand()%100)/10;
}

int main(int argc, char** argv)
{
    int agent_count = 10;
    agent* agent_list = malloc(sizeof(agent)*agent_count);
    for(int i = 0;i<agent_count;i++)
        init_agent(agent_list[i]);

    return 0;
}

我不能为我的生活弄清楚什么是错的。我认为我已经完成了所有事情,但错误让我觉得我在声明类型时可能做错了,或者可能是我声明数组的方式。

轻微编辑:我很累,可能没什么意义 - 本质上我希望能够创建一个代理“对象”,类似于c ++对象,并且能够简单地操作它们。我意识到我可以使用c ++,但我试图更多地了解C,所以我觉得我会在某种程度上作弊。

1 个答案:

答案 0 :(得分:4)

[]订阅运算符取消引用指针。你需要的是

init_agent(&agent_list[i]);

或等效的

init_agent(agent_list + i);

我。即列表中i项的地址,而不是结构本身。