When passing a struct to another function, it would usually be better to do as Donnell suggested above and pass it by reference instead.
A very good reason for this is that it makes things easier if you want to make changes that will be reflected when you return to the function that created the instance of it.
Here is an example of the simplest way to do this:
#include <stdio.h>
typedef struct student {
int age;
} student;
void addStudent(student *s) {
/* Here we can use the arrow operator (->) to dereference
the pointer and access any of it's members: */
s->age = 10;
}
int main(void) {
student aStudent = {0}; /* create an instance of the student struct */
addStudent(&aStudent); /* pass a pointer to the instance */
printf("%d", aStudent.age);
return 0;
}
In this example, the argument for the addStudent()
function is a pointer to an instance of a student
struct - student *s
. In main()
, we create an instance of the student
struct and then pass a reference to it to our addStudent()
function using the reference operator (&
).
In the addStudent()
function we can make use of the arrow operator (->
) to dereference the pointer, and access any of it's members (functionally equivalent to: (*s).age
).
Any changes that we make in the addStudent()
function will be reflected when we return to main()
, because the pointer gave us a reference to where in the memory the instance of the student
struct is being stored. This is illustrated by the printf()
, which will output "10" in this example.
Had you not passed a reference, you would actually be working with a copy of the struct you passed in to the function, meaning that any changes would not be reflected when you return to main
- unless you implemented a way of passing the new version of the struct back to main or something along those lines!
Although pointers may seem off-putting at first, once you get your head around how they work and why they are so handy they become second nature, and you wonder how you ever coped without them!