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 a
to b
, which means that a.p
(char*
) is being assigned to b.p
. Therefore modifying the memory pointed to by b.p
is also modifying the memory pointed to by a.p
, since they're both pointing to the same location in memory.
In the first example, you have two separate arrays. Assigning a
to b
copies each char
in the array a.p
to b.p
- these blocks of memory are part of the struct
, they're not pointers to a specific part in memory. Any modification to b.p
in this case can't affect a.p
since they're completely unrelated.
In your first code, the struct contains an actual character array (char[10]
), so when you copy the struct (b = a
) the array is copied also. Then you overwrite one of them but not the other.
In your second code, the struct contains a pointer to a character, so when you copy the struct the pointer is copied, but the data is not. So both point to the same data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With