0

I think I'm very much confused over how I should be declaring structs and typedefs in C. I've been reading over - and according to this answer, what I'm doing should be correct. I'm trying to declare a simple type (essentially just a vector at the moment), and use it with pointers, but something is very wrong, and I keep getting the error (other compiler output included, including command):

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] 

My code is as follows:

#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; } 

I can't for the life of me work out what's wrong. I think I've done everything correctly, but the error is making me think I've done something wrong in declaring the type, or possibly the way I've declared the array.

Slight edit: I'm tired, and probably not making much sense - essentially I'd like to be able to create an agent "object", similar to c++ objects, and be able to manipulate them simply. I realise that I could just use c++, but I'm attempting to learn more about C, and so I feel like I'd be cheating somewhat.

1
  • 1
    agent_list[i] is an agent. The function wants an agent*. Pass &agent_list[i]. Commented Jun 22, 2013 at 19:58

1 Answer 1

3

the [] subscription operator dereferences pointers. What you need instead is

init_agent(&agent_list[i]); 

or the equivalent

init_agent(agent_list + i); 

i. e. the address of the ith item in the list, and not the struct itself.

Sign up to request clarification or add additional context in comments.

3 Comments

Yup - just realised that as well, thanks though! I think the real problem here though is that I'm an idiot, and I need some sleep.
@AdamHarries Just take a nap :P I was surprised to see you making this mistake because your code looks much cleaner and much more organized (indentation, proper use of malloc(), etc.) than that of a typical beginner who would make such a mistake.
Have done now. Thanks for the compliment! I've been using C for about 5 years now off and on, so I'm pretty ashamed to have made such a trivial mistake.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.