![]() |
VOOZH | about |
In C++, we can assign a struct (or class) variable to another variable of same type. All members of one variable are copied to the other variable. But what happens when the structure contains an array? We will explore it in this article.
Consider the following program:
gfg1.arr[0]: 111 gfg2.arr[0]: 1
In the above program, gfg1 is assigned to gfg2 variable. When gfg1.arr[0] is changed, gfg2.arr[0] remains unchanged indicating that arrays of both variables are stored separately in the memory. It means that array members are copied when structures are assigned. But what if the array is dynamically allocated? Let's see with the help of program,
gfg1.arr[0]: 111 gfg2.arr[0]: 111
As we can see, things changed in this case. Changing the value of gfg1.arr[0] also changed the value of gfg2.arr[0]. We can see what's happening under the hood by carefully examining the code:
It means that,
If the array member is statically declared, the data is copied when one variable is assigned to another. But when the array is dynamically declared, only the address of the dynamically allocated block is copied, but not the data.
In other words, static arrays are deeply copied automatically by compiler but not dynamic arrays. We have to define the assignment operator to perform deep copy.
C Style strings can be declared as both array of character terminated by NULL character as well as pointer to the character. So, from the above, we can infer that if it is declared as static array of character, it will be automatically deeply copied by the compiler. But if it declared as pointer to character, then it will be shallow copied. Though, this does not happen for C++ style strings.
Example 1: Strings as Pointer to Characters
st1's str = XYeksforGeeks st2's str = XYeksforGeeks
Example 2: String as Array of Characters
st1's str = XYeksforGeeks st2's str = GeeksforGeeks