Here is my code.
int main()
{
struct emp
{
char *n;
int age;
};
struct emp e1 = {"Dravid", 23};
struct emp e2 = e1;
strupr(e2.n);
printf("%s\n", e1.n);
return 0;
}
Question 1: The answer as per the website is ‘DRAVID’ that is upper case. Howcome, are e2 and e1 same? i.e. if I do, e2.age++ then will this change be reflected in e1 too?
Question 2: If I change the strupr to strcpy I get seg fault? Why? i.e. If i change it to strcpy(e2.n,"hoho");.
After you construct your two
emps, this is what you have in memory:Now notes, on what you’re trying to do.
strupr(e1.name)is undefined behavior, because you’re not allowed to modify string literals.strcpy(e1.name, e2.name)is also undefined behavior, because strcpy requires that the two pointers passed to it refer to different pieces of memory. Also, its UB because you can’t modify string literals.strcpy(e1.name, "hiho")is also undefined behavior, because you can’t modify string literals.