Passing struct arrays to functions
What you'll learn: How to efficiently pass an entire collection of custom data objects to a function using pointers.
The Mailroom Analogy
Imagine you have a stack of 100 identical forms, each containing a student's name and grade. If you wanted a colleague to grade them all, you wouldn't photocopy every single page and hand them over one by one; that would be a waste of paper and energy. Instead, you would simply hand them the entire folder or tell them, "The stack starts right here on my desk."
In C, passing an array of structures works exactly like that. You don't pass the "value" of the whole array (which could be massive). Instead, you pass the memory address of the first element.
How it works in code
When you pass a struct array to a function, it "decays" into a pointer to the first struct in that array. Because the function only knows where the array starts, you almost always need to pass a second argument: the size of the array. This tells the function when to stop reading so it doesn't wander into restricted memory.
Inside the function, you can use the familiar [] subscript notation to access each individual struct, just like you would with an array of integers.
#include <stdio.h>
struct Student {
char name[20];
int score;
};
// The function receives a pointer to the first struct and the array size
void printClassRoster(struct Student list[], int size) {
for (int i = 0; i < size; i++) {
printf("Student: %s | Score: %d\n", list[i].name, list[i].score);
}
}
int main() {
// An array of 3 Student structures
struct Student classroom[3] = {
{"Alice", 92},
{"Bob", 85},
{"Charlie", 78}
};
// Pass the array name (the address) and the count
printClassRoster(classroom, 3);
return 0;
}
Why this matters
Passing the address is incredibly fast. Whether your array has three students or three million, the "cost" of calling the function is the same because you are only passing a single memory address. Once the function has that address, it can use the struct definition to calculate exactly how many bytes to jump forward to find the next item in the sequence.
Key takeaway
Pass struct arrays by providing the array name and its size; C treats the array name as a pointer to the first element for maximum efficiency.