C Structures and Functions
Structures group values under one name. A function takes that group as one value, and can return one.
Print a struct
A student goes into the print function as one value. The output shows Ada at 20 with a score of 88.
#include <stdio.h>
struct Student {
char name[20];
int age;
int score;
};
void print_student(struct Student s) {
printf("%s is %d.\n", s.name, s.age);
printf("Score: %d\n", s.score);
}
int main() {
struct Student s1 = {"Ada", 20, 88};
print_student(s1);
return 0;
}Return a struct
The make function builds a student and hands it back. The output shows Ben at 19, so the returned group arrived whole.
#include <stdio.h>
struct Student {
char name[20];
int age;
int score;
};
struct Student make_student(void) {
struct Student s = {"Ben", 19, 76};
return s;
}
int main() {
struct Student s1 = make_student();
printf("%s is %d.\n", s1.name, s1.age);
return 0;
}Change through a pointer
Only the address travels this time, so the change lands on the real student. The output shows Cleo at 23, one year older.
#include <stdio.h>
struct Student {
char name[20];
int age;
int score;
};
void add_year(struct Student *s) {
s->age = s->age + 1;
}
int main() {
struct Student s1 = {"Cleo", 22, 91};
add_year(&s1);
printf("%s is %d.\n", s1.name, s1.age);
return 0;
}Example
#include <stdio.h>
struct Student {
char name[20];
int age;
int score;
};
void print_student(struct Student s) {
printf("%s is %d.\n", s.name, s.age);
printf("Score: %d\n", s.score);
}
struct Student make_student(void) {
struct Student s = {"Dan", 21, 80};
return s;
}
void add_year(struct Student *s) {
s->age = s->age + 1;
}
int main() {
struct Student s1 = make_student();
add_year(&s1);
print_student(s1);
return 0;
}Key points
- A function can take a struct as a parameter.
- The struct arrives as a copy, so changes inside stay inside.
- A function can return a struct as its result.
- A function can take a pointer to a struct to change the real one.
- The arrow -> reads a member through a pointer.
- Pass the address with & to let a function change a struct.
- The struct type must be defined before the function that uses it.
Dan is built by one function, aged by another, and printed by a third. The output shows him at 22 with a score of 80, so all three steps worked on the same group.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How does a function change the age of the real struct, not a copy?