How to declare and initialize array of char**

I want to declare and initialize an array of char**,here is my code,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  const char** g_arStr[3] = {
	{
		"one",
		"two",
		"three"
	},

	{
		"me",
		"you",
		"he",
		"her"
	},

	{
		"male",
		"female"
	}
};


but the vs compiler gives the error: error C2440: 'initializing': cannot convert from 'initializer list' to 'const char **'
is there any way to achieve this?
Last edited on
ideally you would use a vector of strings, but if you must..

const char *options[2] = { "1", "2" };

that is an array of strings. I honestly am unclear if you can make a 2d array of strings and keep the const. I can do it without the const, though.

Its unclear if you need that 3rd dimension. You only show 2 in your initialization but 3 in the definition.
Last edited on
That's not an initializer that could ever work with an array of pointers to pointers to char. What do you expect g_arStr[0] (a pointer to pointer to char) to be pointing to? You're offering it {"one","two","three"}, but that's not a pointer to char, and your pointer-to-pointer-to-char can't point to it. (that's what the compiler said "cannot convert from 'initializer list' to 'const char **'")

You could use that iniitalizer with some other types, though:

vector of vectors of pointers:
1
2
3
4
5
6
7
8
9
#include <iostream>
#include <vector>
std::vector<std::vector<const char*>> g_arStr = {{"one","two","three"},{"me","you","he","her"},{"male","female"}};
int main() {
    for(const auto& r : g_arStr) {
        for(const auto& p: r) std::cout << p << ' ';
        std::cout << '\n';
    }
}

demo: https://wandbox.org/permlink/RjcaJhDZZQtcfRwN

vector of vectors of strings:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <vector>
#include <string>
std::vector<std::vector<std::string>> g_arStr = {{"one","two","three"},{"me","you","he","her"},{"male","female"}};
int main() {
    for(const auto& r : g_arStr) {
        for(const auto& p: r) std::cout << p << ' ';
        std::cout << '\n';
    }
}

demo: https://wandbox.org/permlink/1ByUC1JKj6lC3edH

etc.
Last edited on
jonnin: Yes I need 3rd dimension.

Cubbi: It's good to know vector can do this stuff,but I have achieved this way
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const char * g_arstr0[] = {
	"one",
	"two",
	"three"
};

const char * g_arstr1[] = {
		"me",
		"you",
		"he",
		"her"
};

const char * g_arstr2[] = {
	"male",
	"female"
};

const char** g_arStr[3] = {
	g_arstr0,
	g_arstr1,
	g_arstr2
};


I personally prefer array over vector if the element number is fixed.thx all.
Last edited on
I personally prefer array over vector

Strongly prefer std::array over C-style arrays.

Use std::vector by default, unless you have a specific need for something else.
Last edited on
Topic archived. No new replies allowed.