I want to use 2 large bitsets much larger than this example, so I have to use malloc to create them. I manipulate the 1st array "foo" to create a "template" array and then copy it to the 2nd "bar", and then I want to continue to manipulate and use the 2nd array in my program, and when I'm done I want to be able to copy the template "foo" to "bar" again quickly, so I can start over from that point.
#include <bitset>
#include <iostream>
using namespace std;
int main ()
{
long i;
const long size=1000;
bitset<size>* foo;
foo = (bitset<size>*) malloc (sizeof(bitset<size>));
foo->set();
for(i=3;i<1000;i=i+3) { foo->reset(i); }
bitset<size>* bar;
bar = (bitset<size>*) malloc (sizeof(bitset<size>));
bar->set();
std::cout << foo->count() << " " << bar->count() << '\n';
memcpy( &bar, &foo, sizeof(foo) );
std::cout << foo->count() << " " << bar->count() << '\n';
bar->reset(1); bar->reset(2);
std::cout << foo->count() << " " << bar->count() << '\n';
return 0;
}
Output:
667 1000
667 667
665 665
The memcpy line works but when I then make changes in the "bar" bitset it also changes "foo". Instead of the memcpy I can also just do: bar=foo; but again foo is changed when bar changes. There are 2 separate arrays in memory as can be seen from the first cout line where the counts are different.
I assume what happens is both pointers points to the same array in memory after the copy, how can I avoid this so I can save the "template" array for later use?
malloc()here at all?std::bitsetisn't a POD type and at least should be allocated usingnew. It seems you have some serious misconceptions about how all of that works. - πάντα ῥεῖmallocis to be used (even bad C++ books). Where are you getting your reading material in how to write C++ programs? Are you readingCbooks instead ofC++books? - PaulMcKenziesizeof(foo)-- That doesn't work. Thesizeofknows nothing about "dynamic array" sizes. Thesizeofis a compile-time value denoting the size of the type that's specified. Thesizeof(foo)is more than likely going to be either4or8, depending on the pointer size. Basically the code you wrote is fundamentally flawed in multiple areas. - PaulMcKenziememcpy( &bar, &foo, sizeof(foo) );would bebar = foo;You're copying the pointer, not the underlying value. - Sid S