I am newbie to Unions. In the following code, according to my understanding, we are editing a fixed string literal "GeeksQuiz" by trying to replace with 'S' inplace of G. Shouldn't it throw some segfault error. If not then why isn't the answer "SeeksQuiz" and is "GeeksQuiz" ?
# include <iostream>
# include <string.h>
using namespace std;
struct Test
{
char str[20];
};
int main()
{
struct Test st1, st2;
strcpy(st1.str, "GeeksQuiz");
st2 = st1;
st1.str[0] = 'S';
cout << st2.str;
return 0;
}
Let me breakdown what is happening here line by line:
Struct Test st1, st2;
creates two local struct Tests. These are not pointers / references, but the structs themselves.
if you try to print out the structs, they will have random characters since str is not initialized.
strcpy(st1.str, "GeeksQuiz");
Copies the string literal GeeksQuiz to st1.str, so st1.str should have GeeksQuiz with null terminating character.
st2 = st1;
We set st1 to be equal to st2. Both are not pointers or references, (flat objects) so its like
int a = 5;
int b = 6;
a = b; // a = 6
a = 7; // a = 7, b is still 6
So st2.str
= GeeksQuiz, st1.str
= GeeksQuiz, but they (st1, st2) both are separate entities.
st1.str[0] = 'S';
st1.str = SeeksQuiz, st2.str = GeeksQuiz.
cout << st2.str;
st2.str = GeeksQuiz, which is what gets outputted.
We are nowhere trying to change the actual literal itself, anytime we use literals to initialize something, it is copied to that variable. I hope all this clarifies your question.
If st1
and st2
were pointers to structs, then setting st1 = st2
both will point to the same place in memory, so changing something through *st1
will be reflected in *st2
as well, but thats not the case here.