-3

I've a complex structure let's say: a graphe: grapheMAT

I've: grapheMAT* graphe1; initialized by some datas...

what I want is to copy graphe1 to another graphe2, and the modifications that I do on graphe2 won't affect graphe1 ! Can I do that ?

EDIT: my structure has non primitive members to it.

Yassine Bakkar
  • 107
  • 1
  • 13
  • 1
    You can use memcpy if the structure does not contains pointers – terence hill Mar 30 '16 at 12:30
  • Depends on how deep you want your copy to be. For example of your struct type has pointer members, do you also want to duplicate those pointed by them? – user3528438 Mar 30 '16 at 12:30
  • @user3528438 Yes ! i would love to do that !!!! – Yassine Bakkar Mar 30 '16 at 12:32
  • @terencehill which is unlikely for `a complex structure` – Guiroux Mar 30 '16 at 12:32
  • Then you need to write a function to do it. Allocate the top level struct, initialize all pointer members with valid memory and copy data to there, go as further down as you need to. There's no language syntax to do deep-copy for you. You need to write your code to do it. And please update your question to make clear that you want to do `deep copy`. – user3528438 Mar 30 '16 at 12:35
  • @user3528438 done, thank you ! – Yassine Bakkar Mar 30 '16 at 12:38

1 Answers1

1

Yes, of course you can do that. Simply do member-wise copy. For primitive members use

graphe2->primitive_member = graphe1->primitive_member;

but be careful if you use non-primitive members or pointers. For non-primitive data types you may want to do deep copying (depending on how you use those data). See, for example, Copying one struct to another.

We'll be able to give more concrete advice if you provide the definition of the data type.

Community
  • 1
  • 1
blazs
  • 4,705
  • 24
  • 38