passing structure array to function

  • A+

I've been learning C for about 2 months, still a novice:(

I know there are other similar questions on this site. I've read them, but still couldn't really understand, so here I am. Below is my code:

//naming my structure as ball typedef struct ball_room { int enter; int exit; } ball;  //I've omitted some irrelevant details for brevity     int i, n, max;     scanf("%d", &n);     ball person[n];     .../*assign values to ball.enter and ball.exit with user input*/     max = 1;     for (i = 0; i < n; i++)         if (ball_room(person, person[i].enter, n) > max)             max = ball_room(person, person[i].enter, n);     printf("%d/n", max);     return 0; } 

and below is my function receiving the array:

//This function returns the number of people in the ballroom //when b[j](person[j] in "main") enters int ball_room(ball *b, int i, int n) {     int people = 0, j;     for (j = 0; j < n; j++)         if (b[j].enter <= i && b[j].exit > i)             people++;     return people; } 

my question is that why is it b[j].enter instead of b[j]->enter, which my compiler wouldn't accept? In my limited experience, when manipulating structure itself (the object), I use . to go inside the structure, and when it's a pointer (the address), I use -> (hope this is correct.)

And in this case, I pass the array to function using ball *b, which represent the address of person[0], so I can access the whole array. But shouldn't ball *b be in the form of a pointer and therefore I should use -> to access its content? It's just an address that I pass to the function.

This is my first time doing something with an array of structures, please help me get this clear, thank you!


you use . instead of -> because of this declaration of parameters:

int ball_room(ball *b, int i, int n)

b is expected to be pointer to data with type ball, so you can access it in various ways:

  1. array way: e.g. b[5].somefield = 15 - you use dot here, because if b is of type ball *, it means that b is pointer OR it is array of objects with type b, if it's array of objects with type b (which is your case) you use . to access fields of object
  2. pointer way: e.g. (b+5)->somefield = 15 - it will do exactly same thing as code above, but you will access data in pointer way


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: