Reputation: 3
I have this class
class TestClass
{
public:
int* tab;
};
int main()
{
TestClass a;
a.tab[0]=8;
a.tab[1]=5;
TestClass b;
memcpy(b.tab,a.tab,sizeof(int)*2);
cout << b.tab[0] << endl;
return 0;
}
and I want to copy tab from a to b tab. But this code doesn't work. I tried to copy tab to dynamic array and it worked.
TestClass a;
a.tab[0]=8;
a.tab[1]=5;
int* b=new int[2];
memcpy(b,a.tab,sizeof(int)*2);
cout << b[0] << endl;
Can someone explain why first code doesn't work but second works?
Upvotes: 0
Views: 356
Reputation: 29985
You're causing undefined behavior by trying to use the subscript operator with an uninitialized pointer. Instead of doing any of these, use std::vector
or std::array
, depending on what you are trying to achieve:
#include <iostream>
#include <vector>
class TestClass
{
public:
std::vector<int> tab;
};
int main()
{
TestClass a{ { 8, 5 } };
TestClass b{ a };
std::cout << b.tab[0] << '\n';
}
This keeps it simple and maintainable. STL containers have more friendly value semantics and they are in general easier to use, harder to abuse.
Upvotes: 2