[英]How to fill a String inside an array of structures within a structure in 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.