如何复制结构(结构中的结构)并将其填充到C ++中的结构数组中

时间:2015-05-26 13:15:50

标签: c++ arrays pointers structure cen-xfs

我的结构是结构内的结构 如下问题所示: How to dynamically fill the structure which is a pointer to pointer of arrays in C++ implementing xfs

我需要将上述结构的值提取到我创建的另一个结构中。这个结构需要被视为结构数组。

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;
}

上面的代码是在类库中编写的,需要在类库中显示。

但由于内存分配问题,我不得不为我创建的结构获取垃圾值。 我已经成功填写了主要结构((即结构内的结构),我只需要来自这个结构的特定成员

1 个答案:

答案 0 :(得分:1)

你有这个结构:

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

假设LPSTR来自windows types,那么它在大多数现代系统上都是char *的typedef。如果是这种情况,那么您需要为该数组分配内存以及结构的空间。当你为这个结构创建空间时,你留出足够的内存来存储指针和其他2个数据成员,但是指针还没有指向任何有效的东西,你所做的就是放在一边存储poiner的空间。在代码片段中,看起来这里的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中,并创建一个实用程序函数,以便在需要时转换为原始数组

将所有数据保存在容器中,然后在代码的边界进行转换,调用现有库是管理此类情况复杂性的更好方法。