gpt4 book ai didi

C++ 为结构成员设置值**

转载 作者:太空宇宙 更新时间:2023-11-04 13:27:49 24 4
gpt4 key购买 nike

我在我的 foo.h 中定义了以下变量

#define APILONG          long
#define APIDOUBLE double
#define APISTRING const char*

还有下面的结构

struct SetupData
{
APISTRING customerName;
APIDOUBLE quantity;
APILONG startDate;

};

现在,在我的 foo.cpp 中,我有以下方法,我需要为从 .config 文件中提取的结构成员赋值.

APILONG doSomething(APISTRING* setupOrder, APILONG* setupActive, struct SetupData** setupData)
{
//load config file
Config config("rommel.config");

//assign a string value to APISTRING* (No issue here.)
*setupOrder= config.pString("setupOrder").c_str();

//assign a value (No issue here, atleast not that I know of..)
*setupActive = config.pDouble("setupActive");

//assign values to members of struct**
(*setupData)->customerName = config.pString("setupDataCustomerName").c_str();
(*setupData)->quantity = config.pDouble("setupDataQuantity");
(*setupData)->startDate = config.pDouble("setupDataStartDate");

//do other stuff..
}

当我编译和重建时,它没有给我任何错误信息。但是当我尝试运行实际程序时它崩溃了。 (我正在使用 Dev-C++,Visual Studio 导致了问题……) 然而,我确实有机会在它崩溃之前看到分配的值,看起来这些值没有被分配(空字符或奇怪的字符)。

我试过各种变体(*setupData)->startDate ..行,我也试过在如下方法中声明结构,但无济于事。

    struct SetupData stpData;
*setupData = &stpData;

如有任何帮助,我们将不胜感激。我之前发布了另一个与此相关的问题,它也包含一些非常有用的信息。如果有帮助,我会留下链接。 "C++ Set value for a char**"

最佳答案

config 对象是 doSomething 函数的本地对象。

setupOrder 指针指向一个看似config 对象的成员。

config 对象将在 doSomething 函数结束时超出范围,此时可以取消分配。
那时,setupOrder 指针“指向”什么可能不再有效。

最好确保在 doSomething 调用结束后,所有指针仍然指向仍然存在的对象。

您可能已经这样做了,但我只是想检查一下。

关于C++ 为结构成员设置值**,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32744273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com