Hi All,
I've been trying to work out how to pass an array of structs to a function. After googling and doing some trial and error I came up with this;
Code:
#include <stdio.h>
struct frogs
{
int num_eyes;
int num_legs;
}s[3]; //three of em
void build_frogs(struct frogs * f, int n) //Pass pointer to struct frogs
{
int i;
int eyes[3] = {3,4,5}; //Use these to fill our structs
int legs[3] = {5,6,7};
for(i=0; i < n; i++)
{
f->num_eyes = eyes[i];
f->num_legs = legs[i];
f++; //pointer address is array???????
} //So we should be able to do this!!
}
void print_frogs(struct frogs * f, int n) //See above
{
int i;
for(i=0; i < n; i++)
{
printf("Num eyes : %d\n", f->num_eyes);
printf("Num legs : %d\n", f->num_legs);
f++;
}
}
int main(void)
{
build_frogs(&s, 3); //Pass address of struct
print_frogs(&s,3);
return(0);
}
This compiles and when run seems to work and give the right "answers", however my compiler (GCC) gives the following warnings about incompatible pointer types;
Code:
cc -O -pipe struct3.c -o struct3
struct3.c: In function 'main':
struct3.c:47:14: warning: passing argument 1 of
'build_frogs' from incompatible pointer type
[-Wincompatible-pointer-types]
build_frogs(&s, 3);
^
struct3.c:11:6: note: expected 'struct frogs *'
but argument is of type 'struct frogs (*)[3]'
void build_frogs(struct frogs * f, int n)
^
struct3.c:48:14: warning: passing argument 1
of 'print_frogs' from incompatible pointer type
[-Wincompatible-pointer-types]
print_frogs(&s,3);
^
struct3.c:28:6: note: expected 'struct frogs *'
but argument is of type 'struct frogs (*)[3]'
void print_frogs(struct frogs * f, int n)
^
So, having tried various options but only getting the above version to compile, what would be the correct way to declare my functions so as to keep my compiler sweet? A relevant tutorial would be great, as I have not managed to find anything that talks about what I'm trying to do.
Thanks,
greadey