Strings / char arrays inside a structure

I am trying to create a structure containing several arrays of strings inside it. For my purposes, I wanted to use std :: string arrays, but char * arrays would also work if they could do the job. In any case, I cannot figure out how to initialize things. This is what I have:

initialize.h

#include <string>

struct myStruct
{
    std::string x[22];
    std::string y[8];
};

extern myStruct data[22];

myform.cpp

#include <initialize.h>
#include <string>

myStruct data[22];

data[0].x = {"a", "b", "c", "d", ...};

I get errors that look like this:

Error 1 error C2059: syntax error: '{' Error 2 error C2143: syntax error: missing ';' before '{' Error 3 error C2143: syntax error: missing ';' before '}'

I tried various permutations with char * or std :: string * arrays, but to no avail, I was pretty stuck. Did I forget something fundamental?

Thanks in advance.

+3
6

{} . :

int a[3] = { 3, 4, 5 };

int a[3];
a = { 3, 4, 5 }; //error

. , ++ 0x ( ).

0
myStruct data[22];

22 myStruct, x,y , 22,8 .

, . , -

data[0].x[0] = "a";
data[0].x[1] = "b";

// ....

, , -

int a[5] ;
a = { 1,2,3,4,5 } ; // Error.

int a[] = { 1,2,3,4,5 } ; // Correct.
0

  {"a", "b", "c", "d", ...};

,

  std::string data[4] = {"a", "b", "c", "d"};  // syntax allowed for definition

  data[0].x = {"a", "b", "c", "d", ...}; // not definition

( [0].x ). , , .

- ( @Mahesh)

0

++. .

0

char * , . , .

struct myStruct
{
    char * x[22];
    char * y[8];
};

extern myStruct data[22];

myStruct data[22] = {
    { // data[0]
        { "a", "b", "c", ... "v" }, // data[0].x
        { "0", "1", ... "7" } // data[0].y
    },
    { // data[1]
    ...
};
0

Other comments are true, but I believe there is one more thing you can do. You can initialize the structure when you declare it in your header:

struct myStr
{
  string x[22];
  string y[8];
} data[22] = { {...}, {...}, ... };

It will be long and ugly too, but can solve your question. As others have said, you cannot violate this and assign it after creating the instance.

0
source

All Articles