Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between character array and pointer

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?)  
}
like image 991
Anil Arya Avatar asked Jan 06 '12 21:01

Anil Arya


2 Answers

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.

like image 163
AusCBloke Avatar answered Oct 11 '22 08:10

AusCBloke


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.

like image 20
Dan Avatar answered Oct 11 '22 07:10

Dan