Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

copying structs

Status
Not open for further replies.

adev111

Programmer
Jul 8, 2004
44
0
0
CA
Hi there, I have two structs where I am trying to copy from.

typedef struct {
char *netID[7];
int hopCount;
char *nextHop[2];
}Routers;

Routers one;
Routers two;
I read from file and set one.netID = something, one.hopCount = something and etc

How can I set two the same as one?

Can someone please help, its urgent!!
Thanks
 
Since you didn't specify what the "something" is that you want to set netID and nextHop to, I'm not sure of the best way to copy it?

From what I see, netID is an array of 7 strings and nextHop is an array of 2 strings. Is that really what you were trying to make?
 
Code:
typedef struct {           
     char *netID[7];
        int hopCount;                     
        char *nextHop[2];                     
        }ROUTERS;

ROUTERS one;
ROUTERS two;
ROUTERS *three;

// to copy and have two distinct areas with same info
memcpy(&one,&two,sizeof(ROUTERS));

// to have one area of memory with same info
three=&one;

printf("%d",one.hopCount);
printf("%d",three->hopCount);
 
He wants to copy from one to two, I guess.

Code:
ROUTERS one;
ROUTERS two;

memcpy(&(one.netID),&(two.netID),7*sizeof(char*));

Cheers,
Dian
 
Note that this is a shallow copy. Structure copies are legal in C.
Code:
one = two;
 
But not for pointers. It is very risky to copy structures with pointers, unless you really know what you're doing :)

For example, you copy those structures like one = two.
After that, somewhere in code, you call

Code:
free(one.netID[1]);
one.netID[1] = NULL;

BUT, two.netID[1] still contains a "valid" pointer to the memory that is now freed. You use the pointer - you get exception! And spend your next 2 days trying to figure out why a "valid" pointer causes an exception ;)

If you're dealing with pointers, always write your own copy routines, so that you allocate seperate memory blocks for pointers.

------------------
When you do it, do it right.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top