2013-02-04 69 views
-6

我有這樣實現:局部變量的值不見了?

//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, %d\n", localInforTable.sendId, localInforTable->data[0]); // correct data 
} 

void Retrieval::CheckInfoData() 
{ 
    printf("Data %d, %d\n", localInforTable.sendId, localInforTable->data[0]); // sendID is OK but data9[0] is just printing the address 
} 

我想在方法InforTableCallBack複製inforTables到一個局部變量,我可以用其他方法。但是,數據在CheckInfoData()中清理?

+5

請發佈*真實*代碼。構建一個[最小測試用例](http://sscce.org)。 –

+0

拋開所有的錯誤,你不是基本上已經在用'memcpy'來做'你想要的'數據嗎?一般來說,您應該使用帶有C++的拷貝構造函數,而不是'memcpy'。 – Dukeling

+0

我已經更新了真實代碼 – olidev

回答

2

代碼存在各種錯誤。首先,data不指向任何分配的內存。其次,memcpy將無法​​用於用戶定義的不可複製的類型。你可以使用MyData的賦值操作符來代替:

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

爲什麼'memcpy()'不能在用戶定義的類型上工作? –

+0

@Aniket好的,它可以在一些用戶定義的類型上工作,也就是可以輕易複製的類型。 – juanchopanza

+3

讓我想知道OP是否真的在問一些事情,或者只是在拖動 –

0

添加到juanchopanza的回答是:

假設代碼中有一個錯字(如果它真的是memcpy()

memcpy(&data, &otherdata, sizeof(otherdata));根本不起作用正確,因爲data已經是指針了。和'&'上的指針是指針的地址=只是錯誤的用法memcpy