简体   繁体   English

C ++结构访问冲突

[英]C++ struct access violation

I have the following struct defined in the header file: 我在头文件中定义了以下结构:

typedef struct _wfs_cdm_physicalcu
{
    LPSTR           lpPhysicalPositionName;
    CHAR            cUnitID[5];
    ULONG           ulInitialCount;
    ULONG           ulCount;
    ULONG           ulRejectCount;
    ULONG           ulMaximum;
    USHORT          usPStatus;
    BOOL            bHardwareSensor;
} WFSCDMPHCU, * LPWFSCDMPHCU;

And in my code file I try to use it like this: 在我的代码文件中,我尝试像这样使用它:

LPWFSCDMPHCU cdm_physical_cass;
strcpy(cdm_physical_cass->cUnitID, "1234");
cdm_physical_cass->lpPhysicalPositionName = "DISP1";
cdm_physical_cass->bHardwareSensor = FALSE;
cdm_physical_cass->ulInitialCount = 100;

The code compiles fine, however I get access violation on that strcpy so I think the struct is not initialized properly. 代码可以正常编译,但是我在该strcpy上遇到访问冲突,因此我认为该结构未正确初始化。 Any thoughts? 有什么想法吗?

cdm_physical_cass is not initialized/allocated. cdm_physical_cass未初始化/分配。 You have to call 你必须打电话

LPWFSCDMPHCU cdm_physical_cass = new WFSCDMPHCU;

Better would be to use smart pointers (as std::unique_ptr ). 更好的方法是使用智能指针(如std::unique_ptr )。

LPWFSCDMPHCU cdm_physical_cass; is not a struct it's a pointer to a struct of type WFSCDMPHCU . 不是结构,而是指向WFSCDMPHCU类型的结构的指针。 You must allocate memory for the struct pointed to by cdm_physical_cass . 您必须为cdm_physical_cass指向的结构分配内存。 The function WFMAllocateBuffer is recommended for that. WFMAllocateBuffer ,建议使用功能WFMAllocateBuffer

由于LPWFSCDMPHCU是指针而不是struct,因此您需要为该指针(LPWFSCDMPHCU)分配内存(取决于语言,为malloc或new),然后可以使用这些字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM