String/char arrays inside struct - c++

I am trying to create a struct that has multiple string arrays inside of it. For my purposes I wanted to use std::string arrays but char * arrays would also work if they can get the job done. Either way I can't 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 am getting 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 have tried various permutations with char * arrays or std::string * arrays instead but to no avail, I am quite stuck. Did I forget something fundamental?
Thanks in advance.

You cannot use the { } array initialization syntax to assign values to arrays. It can only be used when initializing the array right after definition:
int a[3] = { 3, 4, 5 };
but not
int a[3];
a = { 3, 4, 5 }; //error
you will not get around a loop or a manual initialization of every member. But I think the new C++0x standard improves upon this and makes this (and even more initializer syntax) possible.

myStruct data[22];
With the above statement, you have already created 22 objects of type myStruct and each object having it's own x,y string arrays whose size is 22,8 respectively.
You can only initialize each member of an array directly only while declaration and not during assignment operation. So, you can try -
data[0].x[0] = "a";
data[0].x[1] = "b";
// ....
What the error you are doing is something similar to -
int a[5] ;
a = { 1,2,3,4,5 } ; // Error.
int a[] = { 1,2,3,4,5 } ; // Correct.

The
{"a", "b", "c", "d", ...};
syntax is only allowed when defining a variable, so you could do
std::string data[4] = {"a", "b", "c", "d"}; // syntax allowed for definition
but the line
data[0].x = {"a", "b", "c", "d", ...}; // not definition
is not a definition (data[0].x isn't a new variable). Moreover, since this is not a definition, you can't actually place this code outside of a function.
Somewhere in code you're going to have to manually assign each variable (as #Mahesh's answer suggests)

It's not possible to initialize non static array members in C++. Sorry.

If you make these char * instead of strings, you could get away with a static initializer. It's going to be long and ugly though.
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]
...
};

The other comments are correct but I believe there is one other 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] = { {...}, {...}, ... };
This too will be long and ugly but might address your question. As others have said, you can't extern this and assign to it after instantiation.

Related

How do you directly initialize a char array within a struct without memcpy, strcpy, or {...}?

Here's an example to clarify what I mean:
// A struct with a char array
struct StructA
{
char value[6];
};
char Initializer[6] = "Hello";
// This works
StructA works = { "Hello" );
// This doesn't work
StructA doesNotWork = { Initializer };
#define MyValue "Hello"
StructA alsoDoesNotWork = { MyValue };
Yes, memcpy, strcpy, loops, et. al. can be used to easily accomplish this, but I'd like to just use a direct initialization approach.
I've run into this same issue before and found a solution, but forgot what it was :-(
I'm fairly certain the approach I used last time involved macros in some way.
(Why doesn't the MyValue macro expand to "Hello" anyways?)
How do you directly initialize a char array within a struct without memcpy, strcpy, or {...}?
You can use one a string literal in a default member initialiser:
struct StructA
{
char value[6] = "Hello";
};
If you don't mind using the curly brackets for another object, then you can use that to initialise the another without curlies:
constexpr StructA Initializer { "Hello" };
StructA works = Initializer;
That said, it's unclear why you are against using curly brackets. Don't worry; they won't bite you.
#define MyValue "Hello"
StructA alsoDoesNotWork = { MyValue };
You've named the variable "alsoDoesNotWork". However, this does work. Regardless, I recommend to not use a macro.
(Why doesn't the MyValue macro expand to "Hello" anyways?)
It does.

expected primary-expression before ‘[’ token [duplicate]

This question already has answers here:
Why does C++11 not support designated initializer lists as C99? [closed]
(5 answers)
Closed 6 years ago.
I usually use enums to keep two arrays consistent by defining them like following:
enum foo {
ZERO = 0,
ONE,
TWO,
};
int int_array[] = {
[ZERO] = 0,
[ONE] = 1,
[TWO] = 2
};
char *str_array[] = {
[ZERO] = "ZERO",
[ONE] = "ONE",
[TWO] = "TWO"
};
This code compiles fine for c, but throws following error when used in a cpp module.
expected primary-expression before ‘[’ token
Error is for each line in both array declarations. What's the problem here?
The C++ does not support the so-called designator. Initialization that is allowed in C.
So the compiler issues a message.
In C++ you have to write just the following way
int int_array[] = { 0, 1, 2 };
const char *str_array[] = { "ZERO", "ONE", "TWO" };
^^^^^^
It's not valid syntax for C++. You can initialize arrays in following way:
int int_array[] = { 0, 1, 2 };
char *str_array[] = {
"ZERO",
"ONE",
"TWO"
};

Wrong use of typedef of typedef(?)

I have problem with code from book:
const int SQUARE_ARRAY_SIZE = 4;
const int SQUARE_INFO_SIZE = 4;
typedef Square SquareArray[SQUARE_ARRAY_SIZE];
typedef SquareArray SquareInfo[SQUARE_INFO_SIZE];
SquareArray RedGeneric = { Square(0, 0), Square(0, 1),
Square(1, 1), Square(1, 0) };
SquareInfo RedInfo = { &RedGeneric, &RedGeneric, \\problem here
&RedGeneric, &RedGeneric };
It yells:
error C2440: 'initializing' : cannot convert from 'SquareArray (*)' to 'Square'
IntelliSense: no suitable constructor exists to convert from "SquareArray *" to "Square"
As I understand SquareInfo stands for array of SquareArray but it seems like vs2013 wants to break it to Squares and as result
SquareInfo m_squareInfo; ...
SquareArray* pSquareArray = m_squareInfo[m_iDirection];
yells:
IntelliSense: a value of type "const Square *" cannot be used to initialize an entity of type "SquareArray *"
Book is from 2008 and I don't know if it worked back then or there is error from beginning. As for q please tell me what's really wrong and how to make it work.
I'm fairly sure that the book meant to write
typedef SquareArray* SquareInfo[SQUARE_INFO_SIZE];
// ^
i.e., SquareInfo is an array of pointers to SquareArrays, rather than an array of SquareArrays. This is consistent with initializations using &RedGeneric and SquareArray* pSquareArray = m_squareInfo[m_iDirection];.
Looks like your book has a typo on that line
typedef SquareArray SquareInfo[SQUARE_INFO_SIZE];
When I make this to be a pointer
typedef SquareArray* SquareInfo[SQUARE_INFO_SIZE];
// ^
the code compiles fine.

I got the error C2440:

I got the following error
error C2440: 'initializing' : cannot convert from 'const int' to 'int
[16]'
My code is like this
static int Count[MAX_STATION_NO] = 0;
I got error on above line. Can someone tell me what is the problem in the above line?
You're treating an array as a pointer, which is illegal. You can't assign an array to a value.
Perhaps you want this:
static int Count[MAX_STATION_NO] = {0};
You are creating an array and setting the arrays value to '0'. What I think you wish to do is:
static int Count[MAX_STATION_NO] = {0}
This line is declaring an array of size 16, then you are assigning a single number to it, which is not syntactically correct. You need to use an array initializer:
{ 16, 2, 77, 40, 12071 ... }
Curly brace {} are required to initialize arrays.
eg:
static int Count[MAX_STATION_NO]={1,2,3};
Maybe this link could help you: http://www.cplusplus.com/doc/tutorial/arrays/
Your initializer needs to be in braces:
static int Count[MAX_STATION_NO] = { 0 };
Btw: static arrays have their content initialized with 0 anyway so you the above is equivalent to:
static int Count[MAX_STATION_NO];

Only compiles as an array of pointers, not array of arrays

Suppose I define two arrays, each of which have 2 elements (for theoretical purposes):
char const *arr1[] = { "i", "j" };
char const *arr2[] = { "m", "n" };
Is there a way to define a multidimensional array that contains these two arrays as elements? I was thinking of something like the following, but my compiler displays warnings about incompatible types:
char const *combine[][2] = { arr1, arr2 };
The only way it would compile was to make the compiler treat the arrays as pointers:
char const *const *combine[] = { arr1, arr2 };
Is that really the only way to do it or can I preserve the type somehow (in C++, the runtime type information would know it is an array) and treat combine as a multidimensional array? I realise it works because an array name is a const pointer, but I'm just wondering if there is a way to do what I'm asking in standard C/C++ rather than relying on compiler extensions. Perhaps I've gotten a bit too used to Python's lists where I could just throw anything in them...
No. First, this
char const *combine[][2] = { arr1, arr2 };
cannot work, because arr1 and arr2 cannot be used to initialize an array. But this:
char const *arr1[] = { "i", "j" };
char const *arr2[] = { "m", "n" };
char const *(*combine[])[2] = { &arr1, &arr2 };
works as well as this
char const *arr1[] = { "i", "j" };
char const *arr2[] = { "m", "n" };
char const *combine[][2] = { {"i", "j"}, {"m", "n"} };