局部变量的值消失了

value of local variable is gone?

本文关键字:消失了 局部变量      更新时间:2023-10-16

我有这个实现:

//header file:
InfoTables* localInforTable;
typedef txdr_int32 InfoTable;
typedef struct
{
  int sendID;
  InfoTable *data;
} InfoTables;
// in cpp file
void Retrieval::InfoTableCallBack(int sendID,
                  InfoTables& infoTables)
{
    localInforTable = new InfoTables();
    localInforTable.sendId=sendID;
    localInforTable->data = infoTables.data;
    printf("Data %d, %dn", localInforTable.sendId, localInforTable->data[0]); // correct data
}
void Retrieval::CheckInfoData()
{
    printf("Data %d, %dn", localInforTable.sendId, localInforTable->data[0]); // sendID is OK but data9[0] is just printing the address
}

我想将方法InforTableCallBack中的inforTables复制到一个本地变量中,以便用于其他方法。但是,数据是在CheckInfoData()中清理的?

代码中存在各种错误。首先,data不指向任何已分配的内存。第二,memcpy根本不适用于用户定义的类型,这些类型通常是不可复制的。您可以使用MyData的赋值运算符:

void myMethod1(Mydata &otherdata)
{
  *data = otherdata;
}

添加到juancapanza的答案:

假设代码有拼写错误(如果真的是memcpy()

因为CCD_ 6已经是指针,所以CCD_。和'&'指针上是指针的地址=memcpy 的简单错误使用