Efficiency of passing large structs by pointer
What you'll learn: Why passing a memory address is significantly faster and uses less memory than copying entire data structures into a function.
The Cost of Copying
When you pass a variable to a function by value, C makes a complete copy of that data. If you are passing an int, this is unnoticeable. However, imagine you have a struct representing a high-resolution 3D character model or a large database entry containing dozens of strings and arrays.
Think of it like a physical document. If you want a colleague to edit a 500-page manual, "passing by value" is like going to the photocopier, printing all 500 pages, and handing them the stack. It takes time, uses a lot of paper (RAM), and if they make changes, your original copy stays exactly the same.
Pointing Instead of Printing
Passing by pointer is like handing your colleague a small sticky note with the library shelf location of the manual. Instead of duplicating the data, you give the function a 4-byte or 8-byte memory address. No matter how large the struct is—whether it’s 100 bytes or 100 megabytes—the pointer itself remains the same tiny size.
#include <stdio.h>
struct LargeData {
double coordinates[1000];
char metadata[5000];
};
// EFFICIENT: Only passes an 8-byte address
void processLargeData(struct LargeData *ptr) {
// We access the original data directly via the pointer
ptr->coordinates[0] = 10.5;
}
int main() {
struct LargeData myData;
// We pass the address, not the 13,000+ bytes of data
processLargeData(&myData);
return 0;
}
Speed and Resource Management
In modern programming, efficiency often comes down to how much data you move around. Copying large structs repeatedly can slow your program to a crawl and lead to "stack overflow" errors if the memory limit is exceeded.
By passing a pointer, the CPU does significantly less work. It doesn't have to cycle through memory to duplicate every field of the struct; it simply jumps to the address provided. This makes your functions start and finish much faster, especially in loops or high-performance applications like games or real-time systems.
Key takeaway
Passing a pointer to a large struct saves time and memory because C only has to copy a tiny memory address rather than duplicating every byte of the actual data.