I am doing the same thing in both the codes.
In code 1: I have used a char * and allocate the space using malloc in main.
In code 2: I have used a char array for the same purpose. But why is the output is different ?
Code 1:
struct node2
{
int data;
char p[10];
}a,b;
main()
{
a.data = 1;
strcpy(a.p,"stack");
b = a;
printf("%d %s\n",b.data,b.p); // output 1 stack
strcpy(b.p,"overflow");
printf("%d %s\n",b.data,b.p); // output 1 overflow
printf("%d %s\n",a.data,a.p); // output 1 stack
}
Code 2:
struct node1
{
int data;
char *p;
}a,b;
main()
{
a.data = 1;
a.p = malloc(100);
strcpy(a.p,"stack");
b = a;
printf("%d %s\n",b.data,b.p); //output 1 stack
strcpy(b.p,"overflow");
printf("%d %s\n",b.data,b.p); // output 1 overflow
printf("%d %s\n",a.data,a.p); // output 1 overflow(why not same as previous one?)
}
In the second example you’re assigning
atob, which means thata.p(char*) is being assigned tob.p. Therefore modifying the memory pointed to byb.pis also modifying the memory pointed to bya.p, since they’re both pointing to the same location in memory.In the first example, you have two separate arrays. Assigning
atobcopies eachcharin the arraya.ptob.p– these blocks of memory are part of thestruct, they’re not pointers to a specific part in memory. Any modification tob.pin this case can’t affecta.psince they’re completely unrelated.