AlKnemeyer AlKnemeyer - 2 months ago 18
C++ Question

Pointers with 2D arrays in c++

I'm working on a simple program which uses a 2D array of characters but I think my understanding is off because I'm getting some odd results. I made a class which handles all the text. My constructor looks something like this:

// I use char * <var_name> here, because it's what I've found while searching online,
// but I'm honestly not sure what it *actually* results in in the context of a 2D array
char *options[3][20] = {"text1", "text2", "text3"};
cout << x;
// this displays the same hex address (0x61fd20),
// whether x is options, options[0], *options, *options[0], &options or &options[0] - I have no idea why


Then, later in the same class:

displayOptions () {
cout << &options; // outputs 0x61ff28 (slightly different address)
// any other modifier to options (as shown above) outputs nothing


I know I'm supposed to ask only one thing at a time, so my ultimate question is this: how exactly do I initialise and display the contents of a 2D array?

If related to why I'm getting this wrong, why do all those different variations on "options" print the same thing, and why does it change when the same variable is used in a different method in the same class?

Answer

An array of arrays is different than an array of pointers. In your code, your options array is actually both (an array of arrays of pointers; no joke), and probably unintentionally so.

To have a clearer understanding of your declaration, taking char *options[3][20] to cdecl.org (a most awesome website for learning declaration syntax and worthy of bookmarking) gives us:

declare options as array 3 of array 20 of pointer to char

Given that, what it appears you're trying to do is one of the following:

  • Declare an array of three pointers to constant strings.
  • Declare an array of three char[20] with initial values provided.

Only one of these, the latter, is an array of arrays. The former is an array of pointers to const char data.

Array of three pointers to const strings

The string literals are const, and such should be treated as such. Also note the 3 is optional, as it can be deduced from the initialization:

char const *options[3] = {"text1", "text2", "text3"};

or

char const *options[] = {"text1", "text2", "text3"};

Array of char arrays

No pointers are required. You simply do this (and note again, the 3 is optional, as it is again deducible from the initializer):

char options[3][20] = {"text1", "text2", "text3"};

or

char options[][20] = {"text1", "text2", "text3"};

The two biggest differences between these two approaches

  • One is an array of pointers, the other an array of char arrays
  • For the former, the array (of pointers) is mutable, but the strings are not. For the latter, both the array and the strings (the arrays of char) are mutable.