Deep and Shallow Copy

Learn about types of copying data and their crucial differences. Learn how to avoid making common mistakes when copying structures, which can lead to hard-to-track bugs.


Copying structures is a common and useful operation. However, it can raise a subtle problem. What happens when structures contain pointer members or other resources (file descriptors, sockets, and so on)? To answer the question, we’ll consider the following example. We’ll model an employee structure, which may contain the following data:

  • Employee’s name
  • Employee’s ID
  • Employee’s salary

Starting code

Let’s transpose this scenario in code. We define the structure at lines 4–9. Inside main, we create two employees at lines 13–14. We then print the members of e1 and e2 to see if the code works fine.

Get hands-on with 1200+ tech skills courses.