talel
talel

Reputation: 355

Dynamic string array allocation error

I am trying to allocate a dynamic string array in the following way and I get an error:

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

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

The error i get is that there are too many initializers for std::string[0], but if I get off the array part it works:

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

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

Thanks in advance!

Upvotes: 0

Views: 561

Answers (2)

user1149224
user1149224

Reputation:

You can use C++11 uniform initialization:

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

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

The following sample code compiles fine with 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;
}

Upvotes: 1

littleadv
littleadv

Reputation: 20262

You cannot initialize zero-sized arrays this way, because you have to dynamically allocate the memory. You can only do what you do if you specify the dimensions in the type definition.

See my answer to a similar question here.

Upvotes: 3

Related Questions