c - 对 C typedef 结构的普遍误解,以及与指针的关系

标签 c pointers gcc struct typedef

我想我对如何在 C 中声明结构和类型定义感到非常困惑。我一直在阅读 - 并且根据 this回答,我做的应该是正确的。我正在尝试声明一个简单类型(目前本质上只是一个 vector ),并将其与指针一起使用,但出现了一些错误,我不断收到错误消息(包括其他编译器输出,包括命令):

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 的知识,所以我觉得我有点作弊。

最佳答案

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

init_agent(&agent_list[i]);

或等价物

init_agent(agent_list + i);

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

关于c - 对 C typedef 结构的普遍误解,以及与指针的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17254748/

相关文章:

c - 制作一个简单的HTTP网络服务器,使用errno回复 "403 Forbidden",然后重定向到403页面?

c - 如何在 C 中读取字符数组并通过错误检查将其转换为整数?

C语言指针和数组

c++ - C和C++中的全局变量有什么区别?

c - 确定描述符是套接字还是 Windows 上的常规文件?

我可以部分/选择性地内联函数吗?

c++ - 如何防止将空指针转换为引用

c - 为什么 "*(&arr+4)"与 "&arr[4]"不同?

gcc - CUDA 8.0 现在与 gcc 5.4 兼容吗?

c - 如何将源文件路径提供给 gcc?