By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,516 Members | 1,369 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,516 IT Pros & Developers. It's quick & easy.

Can we copy structures with "=" operator?

P: 4
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?
Oct 7 '10 #1
Share this Question
Share on Google+
1 Reply


ashitpro
Expert 100+
P: 542
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.
Oct 7 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.