8

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?)  
}
AusCBloke
  • 18,014
  • 6
  • 40
  • 44
Anil Arya
  • 3,100
  • 7
  • 43
  • 69

3 Answers3

10

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.

AusCBloke
  • 18,014
  • 6
  • 40
  • 44
3

Character pointers and character arrays are not the same thing.

Your node with the array is getting copied, so the contents are copied into the new node. When you put the new value (overflow) into the copied node (b), it only overwrites the copy.

Your node with the character pointer is getting the pointer's value copied, so both nodes point to the same memory location. When you put the new value (overflow) into the copied node (b), it writes to the memory that both nodes have a pointer to.

That Chuck Guy
  • 443
  • 4
  • 12
3

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.

Dan
  • 10,531
  • 2
  • 36
  • 55