簡體   English   中英

如何復制結構(結構中的結構)並將其填充到C ++中的結構數組中

[英]How to copy a structure(which is a structure within structure) and fill it in the array of structure in C++

我有一個結構,如下面的問題所示,該結構位於結構內部: 如何動態填充該結構,該結構是在實現xfs的C ++中指向數組的指針

我需要將上述結構的值提取到我創建的另一個結構中。該結構應視為結構數組。

typedef struct Sp_cashinfo
{
    LPSTR lpPhysicalPositionName;
    ULONG ulInitialCount;
    ULONG ulCount;  
}SP_CASHUNITINFO;

該結構是結構的數組,因為我需要以2D形式存儲(即7次)

int CashUnitInfo(SP_CASHUNITINFO *Sp_cdm_cashinfo)
 {
     try
    {
        -----assigned the values----------------
        hResult = WFSGetInfo (hService,dwCategory,lpQueryDetails,dwTimeOut,&lppResult); //assigned the values ,got the response 0 ie success    
        fwCashUnitInfo = (LPWFSCDMCUINFO)lppResult->lpBuffer;               
        USHORT NumPhysicalCUs;
        USHORT count =(USHORT)fwCashUnitInfo->usCount;
        Sp_cdm_cashinfo = (SP_CASHUNITINFO*)malloc(7*sizeof(SP_CASHUNITINFO));      
        for(int i=0;i<(int)count;i++)
        {
    NumPhysicalCUs =fwCashUnitInfo->lppList[i]->usNumPhysicalCUs;
    for(int j=0;j<NumPhysicalCUs;j++)//storing the values of structure
    {
        Sp_cdm_cashinfo[i].lpPhysicalPositionName   =fwCashUnitInfo->lppList[i]->lppPhysical[j]->lpPhysicalPositionName;
        Sp_cdm_cashinfo[i].ulInitialCount           =fwCashUnitInfo->lppList[i]->lppPhysical[j]->ulInitialCount;
    }
    }
 return (int)hResult;
}

以上代碼是在類庫中編寫的,需要在類庫中顯示。

但是由於內存分配問題,我不得不為我創建的結構獲取垃圾值。 我已經成功填寫了主結構(即結構內的結構),並且只需要該結構中的特定成員

您具有以下結構:

typedef struct Sp_cashinfo
{
    LPSTR lpPhysicalPositionName;
    ULONG ulInitialCount;
    ULONG ulCount;  
}SP_CASHUNITINFO;

假設LPSTR來自Windows類型,那么在大多數現代系統上,它都是char *的typedef。 如果是這種情況,則需要為該數組分配內存,並為結構分配空間。 當您為該結構創建空間時,您會留出足夠的內存來存儲指針和其他2個數據成員,但是指針尚未指向有效的任何內容,您所要做的就是留出足夠的空間來存儲指針。 在代碼片段中,看起來這里的char數組從未真正分配過任何內存,因此沒有垃圾值。

但是,我會將此結構更改為更慣用的c ++設計,如下所示:

#include <string>
struct Sp_cashinfo
{
    std::string lpPhysicalPositionName;
    uint32_t ulInitialCount;
    uint32_t ulCount;   

    Sp_cashinfo(std::string name, uint32_t initialCount, uint32_t count):
        lpPhysicalPositionName(name),
        ulInitialCount(initialCount),
        ulCount(count)
        {}
};

由於使用這種方法進行內存管理要容易得多。 然后,您可以將這些結構存儲在一個std::vector ,使效用函數轉換為原始陣列如果需要的話

將所有數據保存在容器中,然后在調用現有庫的代碼邊界處進行轉換,是管理此類情況復雜性的更好方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM