[英]General misunderstanding over C typedef struct, and relationship to pointers
我想我應該如何在C中聲明結構和typedef感到非常困惑。我一直在閱讀-根據這個答案,我在做什么應該是正確的。 我正在嘗試聲明一個簡單的類型(目前基本上只是一個向量),並將其與指針一起使用,但是有些錯誤,並且我不斷收到錯誤消息(包括其他編譯器輸出,包括命令):
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);
即列表中第i
個項目的地址 ,而不是結構本身。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.