动态字符串数组分配错误

时间:2012-04-02 07:18:52

标签: c++

我试图以下列方式分配动态字符串数组,但我收到错误:

struct Test
{
    std::string producer[];
    std::string golden[];
};

Test test1 =
{
        {"producer1", "producer2"} ,
        {"golden1"  , "golden2"}
};

我得到的错误是std::string[0]的初始化程序太多, 但如果我离开阵列部分就可以了:

struct Test
{
    std::string producer;
    std::string golden;
};

Test test1 =
{
        "producer1" ,
        "golden1"
};

提前致谢!

2 个答案:

答案 0 :(得分:3)

您不能以这种方式初始化零大小的数组,因为您必须动态分配内存。只有在类型定义中指定尺寸时才能执行操作。

请参阅我对类似问题的回答here

答案 1 :(得分:1)

您可以使用C ++ 11 统一初始化

struct Test
{
    vector<string> producer;
    vector<string> golden;  
};

Test test1 =
{
    {"producer1", "producer2"},
    {"golden1", "golden2"}
};

以下示例代码使用g ++进行编译:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

struct Test
{
    vector<string> producer;
    vector<string> golden;  
};


ostream & operator<<(ostream & os, const Test & test)
{
    os << "------------------------" << endl;
    os << "producer={" << endl;
    for (auto& p : test.producer)
    {
        os << '\t' << p << endl;
    }
    os << "}" << endl;

    os << "golden={" << endl;
    for (auto& p : test.golden)
    {
        os << '\t' << p << endl;
    }
    os << "}";
    os << "------------------------" << endl;

    return os;   
}



int main()
{
    Test test1 =
    {
         {"producer1", "producer2"},
         {"golden1", "golden2"}
    };

    cout << test1 << endl;


    return 0;
}