initilizing an array of string from the define directive

I am trying to compile the below code:
error: expected primary-expression before ‘{’ token

Is there a better way to handle this.

.h:
#define fromdefine1 "name1","name2", ....
#define fromdefine2 "company1","Company2", ....
struct mystruct
{
string names[5];
....
};

.cpp:
mystruct myst;
if (condition)
{
myst.names = {fromdefine1};
}
else
{
myst.names = {fromdefine2};
}

Thanks in advance
You can't assign values to the array that way, that syntax is only valid for initialization.
Why don't you use vectors?
1
2
3
4
5
6
7
8
9
//Header
//declare the vectors
vector<string> fromdefine1, fromdefine2;//You can make those static members for mystruct
void InitVectors();
struct mystruct
{
     vector<string> names;
     //...
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//Source
//set values to vectors
void InitVectors()
{
    fromdefine1.push_back("name1");
    //...
}

//Entry point
int main()
{
     InitVectors();//call the function that will set the values for your vectors
     //...
}

//Somewhere
{
    myst.names = condition ? fromdefine1 : fromdefine2;
}
Thanks for your help. I will try it.

In the mean time, I got it working using va_list:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//Header
#include <iostream>
#include <cstdarg>

#define ASIZE 2
#define FROMDEFINE1 "name1","name2"
#define FROMDEFINE2 "company1","Company2"

using namespace std;

struct mystruct
{
        string *names;
	//....
};
string* getAstr(int Asize, ...);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//Source
int main()
{
        // Lets say condition is 1
        int condition = 1;
        mystruct myst;
        if (condition == 1)
        {
                myst.names = getAstr( ASIZE, FROMDEFINE1 );
                //..
        }
        else if (condition == 2)
        {
                myst.names = getAstr( ASIZE, FROMDEFINE2);
                //..
        }
        //...
        cout << myst.names[0] << endl;
        cout << myst.names[1] << endl;
        delete [] myst.names;

        return 0;
}

string* getAstr(int Asize, ...)
{
        string *arr = new string[Asize];
        va_list args;
        va_start(args, Asize );
        int lenAsize = Asize;

        for(int i=0 ; i < lenAsize; i++ )
        {
                arr[i]= va_arg(args, char* );
                Asize--;
        }

        va_end( args );
        return arr;
}


Output:

name1
name2
Last edited on
Topic archived. No new replies allowed.