Closed. This question needs details or clarity。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                        
                        3年前关闭。
                                                                                            
                
        
我试图在构造函数中为结构数组动态分配存储。我是C ++的新手,曾经尝试过各种语法变体,但现在我想知道是否可以完全做到这一点。

struct Trade
{
    int index;
}

define MAX_TRADES 5000
struct foo
{
    Trade *trade [MAX_TRADES];

    int cumeTradeCount;

    foo() :
        cumeTradeCount(0),
    {
        // here is where I want to allocate storage for cumeTradeCount Trade structures
        ....

        memset(trade, 0, cumeTradeCount   * sizeof(Trade*));
    }
}


具体来说,我要弄清楚的是如何在构造函数中为“ cumeTradeCount”结构分配存储空间。
如果我在C中执行此操作,则将执行以下操作:

for (int i = 0; i < cumeTradeCount; ++i)
    trade[i] = calloc(1, sizeof(Trade *));

最佳答案

You need to read a good C++ book.。您的代码在堆栈上分配了5000个指针。

要在堆栈上分配5000个Trade对象,只需使用Trade trade[MAX_TRADES] ...示例:

struct Trade
{
    int index;
};

#define MAX_TRADES 5000
struct foo
{
    Trade trade[MAX_TRADES];

    int cumeTradeCount;

    foo() :
        cumeTradeCount(0)
    {
        // allocate storage for cumeTradeCount Trade structures
        //memset(trade, 0, cumeTradeCount   * sizeof(Trade*));
        // You don't need it
    }
};


对于堆,您可以使用运算符new在堆上进行分配。

将此内容从Trade *trade [MAX_TRADES];更改为Trade *trade = new Trade[MAX_TRADES];

由于它是班级成员,因此下面是完成的方法。但是请不要忘记在析构函数中使用delete ...下面的完整示例...

struct Trade
{
    int index;
};

#define MAX_TRADES 5000
struct foo
{
    Trade *trade;

    int cumeTradeCount;

    foo() : trade(new Trade[MAX_TRADES]),
        cumeTradeCount(0)
    {
        // allocate storage for cumeTradeCount Trade structures
        //memset(trade, 0, cumeTradeCount   * sizeof(Trade*));
        // You don't need it
    }

    ~foo() { delete[] trade; }
};


。我强烈建议您使用std::arraystd::vector代替原始数组。同样,在C ++中,我们更喜欢使用constconstexpr#defines->仍然You need to read a good C++ book.

下面,将为您节省许多不可预见的麻烦。

#include <vector>
struct Trade
{
    int index;
};

#define MAX_TRADES 5000
struct foo
{
    std::vector<Trade> trade;
    int cumeTradeCount;

    foo() : trade(MAX_TRADES),
        cumeTradeCount(0)
    { }
};

关于c++ - 在C++构造函数中分配结构数组的存储空间,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35690362/

10-10 14:06