Copying structs with the assignment operator
What you'll learn: How to instantly duplicate all the data from one structure variable to another using a single equals sign.
The Instant Photocopy
In C, when you work with basic variables like integers, copying is easy: a = b;. But when you have a struct containing ten different pieces of information, you might worry that you have to copy every single member manually, line by line.
Fortunately, C treats a struct as a single "package." Just as you can photocopy a multi-page contract in one go rather than re-typing every sentence, you can use the assignment operator (=) to copy every member of a struct at once.
How it Works
When you assign one struct variable to another of the same type, C performs a shallow copy. It looks at the block of memory occupied by the source struct and copies it bit-for-bit into the destination struct's memory.
#include <stdio.h>
struct Player {
int score;
int level;
};
int main() {
struct Player player1 = {2500, 10};
struct Player player2;
// The "Photocopy": player2 now has the same data as player1
player2 = player1;
printf("Player 2 Score: %d\n", player2.score); // Outputs 2500
// Changing player2 does NOT affect player1
player2.score = 5000;
printf("Player 1 Score is still: %d\n", player1.score); // Outputs 2500
return 0;
}
Important Considerations
There are two things to keep in mind to use this effectively:
- Type Match: You can only use the
=operator between two structs of the exact same type (e.g., twostruct Playervariables). You cannot assign astruct Enemyto astruct Player, even if they have the same internal members. - Independent Lives: Once the copy is done, the two variables are completely independent. Changing the
scoreofplayer2does not change thescoreofplayer1. They are two separate folders containing the same initial information.
This feature is incredibly powerful for saving the state of an object or passing data around your program without writing repetitive boilerplate code.
Key takeaway
You can use the = operator to copy all data from one struct to another of the same type in a single step.