Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializing a const multidimensional array in c++

I'm currently working through some exercises in a c++ book, which uses text based games as its teaching tool. The exercise I am stuck on involves getting the pc to select a word from a const array of words (strings), mixing the letters up and asking the player to guess the word. This was easy, but as a follow on the book asks to add the option to provide a hint to the player to help them guess, firstly as a parallel array (again, no problem) and then as a 2 dimensional array. This is where I'm stuck. My (shortened) array of words is as follows:

const string WORDS[NUM_WORDS] = {"wall", "glasses"};

I need to provide a hint for each of these words but not sure how to go about it. Posting this from phone so extensive googling is not an option!

My parallel array was as follows:

const string HINTS[NUM_WORDS] = "brick...", "worn on head"};

Just need to combine the two.

Thanks in advance, Barry

like image 561
barry Avatar asked Nov 02 '09 18:11

barry


People also ask

How do you declare and initialize a multidimensional array explain by example?

Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their declaration with a list of initial values enclosed in braces. Ex: int a[2][3]={0,0,0,1,1,1}; initializes the elements of the first row to zero and the second row to one. The initialization is done row by row.


2 Answers

you could make 2d array?

string aArray[][2] = {{"wall", "brick..."}, 
                               {"glasses", "corrective eye tool thingymajig"},
                               {"calculator", "number cruncher"}};

not sure if the syntax is right but i hope you get the concept.

it's an array inside another array.

EDITED: i removed the NUM_WORDS from the first square bracket. you can't declare multi dimentional array from variables.. sorry i forgot about that. i just tested it and it works.

like image 75
user200632 Avatar answered Oct 27 '22 00:10

user200632


Use a struct array:

typedef struct
{
    string Word;
    string Hint;
}
WORDDEF;

const WORDDEF WordList[] =
{
    {"wall", "brick..."},
    {"glasses", "worn on head"},
    ...
};

Then you refer to them as:

printf ("For entry %d, Word is %s, Hint is %s\n", 1, WordList[1].Word, WordList[1].Hint);
like image 21
Graham Avatar answered Oct 26 '22 23:10

Graham