将结构复制到新结构



我正在尝试将struct的成员复制到新的成员中,并对它们进行一些调整。我正在尝试打印成员的值,但它正在打印地址。我已经对这些部分进行了评论。

#include <iostream>
using namespace std;
struct MyStruct
{
char *name;
int * countSize;
};
MyStruct * stCpy(MyStruct *oldStru) //pass the address of the struct and it copies its content
{
MyStruct * newStru = new MyStruct; //allocating the memory
newStru -> name = oldStru -> name; //copying the name
newStru -> countSize = oldStru -> countSize -1; //setting the size to the size of arg struct -1;
return newStru;
}
int main()
{
int size = 10;
char name = 'R';
MyStruct myStrt{&name, &size};
MyStruct * Strtptr = stCpy(&myStrt);
cout <<"printing the name of newstruct" << Strtptr -> name <<endl; //prints the name fine.
cout <<"printing the size of newStruct" << Strtptr -> countSize; // why is this printing the address instead?
return 0;
}
cout <<"printing the size of newStruct" << Strtptr -> countSize; // why is this printing the address instead?

因为您正在打印Strptr->countSize的指针值。要打印的是coutSize所指向的值。

cout <<"printing the size of newStruct" << (*Strtptr -> countSize);

首先,由于@cdhowie建议不需要堆分配以及int*char*,您需要考虑c++方式;

简化您的程序:

struct MyStruct
{
std::string name;
int countSize;
/* copy constructor */
MyStruct(): name(""), countSize( 0 ) {}
MyStruct( const std::string& n, const int& s ): name( n ), countSize( s ) {}
MyStruct( const MyStruct& other )
{
name = other.name;
countSize = other.countSize;
}

};

int main()
{
int size = 10;
std::string name = "stackoverflow";
MyStruct m1( name, size );
MyStruct m2( m1 );
std::cout <<"printing the name of newstruct " << m1.name << std::endl; 
std::cout <<"printing the size of newStruct " << m1.countSize << std::endl;
return 0;
}

为了回答你的问题,无论如何都要使用邪恶的指针;

在下面的行中,您并没有减少它所指向的值,而是您要求指向不同的地址,这可能导致UB

newStru->countSize = oldStru->countSize -1; //setting the size to the size of arg struct -1;

如果您cout地址;你会看到不同,通过你的方式,现在newStru->countSize没有指向oldStru->countSize的地址;

std::cout << "oldStru: " << oldStru -> countSize << std::endl; //0x7ffdd14e7464
std::cout << "newStru: " << newStru->countSize << std::endl; //0x7ffdd14e7460

您需要newStru->countSize指向oldStru->countSize的同一地址;

最新更新