-2

In C++, there is overloaded copy constructor and assignment overloading for a deep copy. Since default available is a shallow copy.

In C, the structure which has pointer member, if passed to a function or assigned to already created new struct object is a deep copy or shallow copy??

E.g

struct data {
    int a;
    int *b;
};

void test_func(struct data tes)
{

    tes.a =3;
    int *c = new int[1];
    c[0]=2;
    tes.b =c;
    std::cout<<*tes.b;

}
int main() {
    struct data test;
    int *c = new int;
    *c=4;

    test.a = 1;
    test.b =c;



    std::cout<<*test.b;
    test_func(test);

    std::cout<<*test.b;

}
Laxmi Kadariya
  • 1,103
  • 1
  • 14
  • 34

1 Answers1

5

A structure in C is simply copied as with memcpy. So you get a copy of the pointer but not a copy of the content which is the pointer pointing to. There is nothing different to c++ in that case.

In C you can also write a function for "deep copy" if you like. Every kind of OOP can be done with C but you have to write each and everything by hand.

Klaus
  • 24,205
  • 7
  • 58
  • 113