----- Original Message -----
From: "Rashmi Vittal" <rashmivittal@yahoo.com>
To: <C-Guru@yahoogroups.com>
Sent: Wednesday, April 28, 2004 3:27 PM
Subject: [C-Guru] strcpy of two addresses


> Hi, here is a problem
>
> struct a {
>             int x;
>             char y;
>            }
>
> struct a i, j;
>
>       i.x =10;
>       i.y = 'a';
>
> strcpy(&j,&i);

    This is a bad idea to use strcpy() to copy a members of a structure to
another.  And, also that you have not casted the arguments to (char*).  Since
from C89 (but, I am not sure) structures have become first class citizens, i.e.,
they can be assigned.  So, your problem solves by

    j = i;

    Anyway, let's see what effects, and ill ones, strcpy can have in this
context.

>
> What happens at strcpy ( the whole process - how
> memory is allocated ,
> etc etc).
>
> Thanks
> Rashmi

    In a little endian machine, the variable "i" will appear in the memory
as:

  0x1000  +0   +1   +2   +3
         ___________________
    x:  | 10 |  0 |  0 |  0 |
         -------------------
    y:  | 'a'|  0 |  0 |  0 |
         -------------------
  0x1000  +4   +5   +6   +7

    With this picture, let us see how strcpy() would work:

    +   strcpy() copies the source to destination byte-by-byte
    +   So, the first byte is decimal 10 (as shown above); copy it
    +   Increment the pointer which happens to be a character pointer
    +   Whoa!  Whoa!  We encounter a zero, the terminating condition for strcpy!
    +   strcpy() thus returns without doing what was intended

    The following program illustrates these points.  My processor is X86, a
little endian.

        F:\Vijay\C> type ill_strcpy.c
        #include <stdio.h>
        #include <string.h>

        struct A {
            int a;
            char b;
        };

        int
        main ( void )
        {
            struct A b, a = { 10, 'a' };

            strcpy ( (char*)&b, (char*)&a );
            printf ( "a:%d\nb:%c", b.a, b.b );

            return 0;
        }

        F:\Vijay\C> gcc -Wall ill_strcpy.c
        F:\Vijay\C> a.exe
        a:10
        b:^@

    In a big endian machine, the variable "i" will appear in the memory as:

  0x1000  +0   +1   +2   +3
         ___________________
    x:  |  0 |  0 |  0 | 10 |
         -------------------
    y:  |  0 |  0 |  0 | 'a'|
         -------------------
  0x1000  +4   +5   +6   +7

    The strcpy() function encounter a zero in the beginning, and will return
immediately.  As you can see, copying structures using strcpy() will have
different effects on little and big endian machines.