Can we copy structures with "=" operator?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • FerozAhmed
    New Member
    • Sep 2010
    • 4

    #1

    Can we copy structures with "=" operator?

    Hi,
    I have a structure as follows.

    typedef struct {
    int a;
    char *c;
    int s;
    }MEDIA;

    main()
    {
    MEDIA m, n;
    char c[] = "feroz";

    m.a = 5;
    m.c = c;
    m.s = 10;

    n = m; ->>>>> is this valid?
    }

    can i use "=" operator to copy data of "m" to "n"?
    will it works on all compilers?
    Is there any restriction on this?
  • ashitpro
    Recognized Expert Contributor
    • Aug 2007
    • 542

    #2
    You can copy, compiler will not give any error.
    But this is not a safe way.

    In your structure there is a pointer variable, essentially it will store some address. If you directly copy the structure object it will only going to copy the address and not the actual data pointed by that pointer.

    So if somewhere in the flow your first object i.e. 'm' gets out of scope, then all memory will be de-allocated and pointer in 'n' object will point to nothing.

    This is typically called as dangling pointer.

    Comment

    Working...