30

Question is in the title, how do I initialize a char*[] and give values to it in C++, thank you.

Romain
  • 12,679
  • 3
  • 41
  • 54
DogDog
  • 4,820
  • 12
  • 44
  • 66

8 Answers8

22

Though you're probably aware, char*[] is an array of pointers to characters, and I would guess you want to store a number of strings. Initializing an array of such pointers is as simple as:

char ** array = new char *[SIZE];

...or if you're allocating memory on the stack:

char * array[SIZE];

You would then probably want to fill the array with a loop such as:

for(unsigned int i = 0; i < SIZE; i++){
    // str is likely to be an array of characters
    array[i] = str;
}

As noted in the comments for this answer, if you're allocating the array with new (dynamic allocation) remember to delete your array with:

delete[] array;
Stephen Cross
  • 1,003
  • 1
  • 8
  • 19
  • 1
    `char ** array = new char[SIZE];` should be `char ** array = new char *[SIZE];` – xian Feb 10 '10 at 20:35
  • 1
    You may also remind that if array is allocated dynamically it should be deleted using `delete [] array` (using `delete array` is a current newbie mistake). – kriss Feb 10 '10 at 20:52
13

Depending on what you want to initialize to you could do any of:

char mystr[] = {'h','i',0};
char * myotherstring = "my other string";
char * mythirdstring = "goodbye";

char * myarr[] = {0};
char * myarr[] = {&mystr, myotherstring};
char * myarr[10];
char * myarr[10] = {0};
char * myarr[10] = {&mystr, myotherstring, mythirdstring, 0};

etc. etc.

John Weldon
  • 39,849
  • 11
  • 94
  • 127
  • Wouldn't `&mystr` and `&myotherstring` resolve to a type of `char[]*`, which isn't the array initializer's expected `char*`? – Romain Feb 10 '10 at 20:33
  • I edited my answer slightly, and as it is now it should work. – John Weldon Feb 10 '10 at 20:34
  • There is also the issue of the difference between a char * and a const char * My compiler use to raise a warning whenever I try to assign a const char * (constant strings) to a char *. – kriss Feb 10 '10 at 20:43
  • 1
    ya... this was really intended to demonstrate initialization rather than compiler satisfaction :) – John Weldon Feb 10 '10 at 20:56
  • To fix g++ errors: `char mystr[] = {'h','i',0}; const char * myotherstring = "my other string"; const char * mythirdstring = "goodbye"; char * myarr[] = {0}; const char * myarr1[] = {(char *)&mystr, myotherstring}; char * myarr2[10]; char * myarr3[10] = {0}; const char * myarr4[10] = {(char *)&mystr, myotherstring, mythirdstring, 0};` – Jonathan Ben-Avraham Sep 30 '14 at 14:59
11

One thing I have noticed that you must be careful of... C and C++ have diverged a bit in initialization syntax. As Mark B. points out above, you can initialize an array of char pointers thusly:

const char* messages[] =
{
    "Beginning",
    "Working",
    "Finishing",
    "Done"
};

But in C++. as kriss points out, this nets you a warning about a deprecated conversion from string to char*. That's because C++ assumes you'll want to use strings for strings ;-}.

That's not always true. So when you really do want to initialize an array of char*, I have found that I have to do it like so:

const char* messages[] =
{
    (char*)("Beginning"),
    (char*)("Working"),
    (char*)("Finishing"),
    (char*)("Done")
};

The compiler is now happy...

Don Doerner
  • 141
  • 1
  • 5
  • std::string gets a bit heavy when working in C++ for embedded devices. Resources are rather limited and std::string adds quite a bit of overhead that serves no purpose for simple string contants. I certainly appreciate this advice, as tedious as it can be for large arrays of string contants. – guitarpicva Oct 25 '22 at 20:20
7

Like this:

char* my_c_string;
char* x[] = { "hello", "world", 0, my_c_string };
Max Shawabkeh
  • 37,799
  • 10
  • 82
  • 91
  • This is very good example. 0 would help in terminating the loop as well if any function just takes argument as void foo( char * x[] ) you don't need to have another variable to find the length of the array. – siddhusingh Oct 04 '14 at 07:32
2

Like that:

char p1 = 'A';
char p2 = 'B';
char * t[] = {&p1, &p2};

std::cout << "p1=" << *t[0] << ", p2=" << *t[1] << std::endl;

But somehow I believe that's not the answer to the real question...

I you want an array of C strings defined at compile time you should use an array of const char * instead:

const char * t2[] = {"string1", "string2"};

std::cout << "p1=" << t2[0] << ", p2=" << t2[1] << std::endl;

Without the const my compiler would say : warning: deprecated conversion from string constant to ‘char*’

kriss
  • 23,497
  • 17
  • 97
  • 116
2

If you really just want a C-style array of constant strings (for example indexed messages):

const char* messages[] =
{
    "Beginning",
    "Working",
    "Finishing",
    "Done"
};

If however you're trying to maintain a container of runtime variable strings, using the C++ facility std::vector<std::string> will make keeping track of all the memory operations much easier.

std::vector<std::string> strings;
std::string my_string("Hello, world.")
strings.push_back("String1");
strings.push_back(my_string);
Mark B
  • 95,107
  • 10
  • 109
  • 188
1

Just like any other array:

char *a, *b, *c;
char* cs[] = {a, b, c}; // initialized
cs[0] = b; // assignment
Peter Alexander
  • 53,344
  • 14
  • 119
  • 168
1
#include <iostream>

int main(int argc, char *argv[])
{
    char **strings = new char *[2]; // create an array of two character pointers
    strings[0] = "hello"; // set the first pointer in the array to "hello"
    strings[1] = "world"; // set the second pointer in the array to "world"

    // loop through the array and print whatever it points to out with a space
    // after it
    for (int i = 0; i < 2; ++i) {
        std::cout << strings[i] << " ";
    }

    std::cout << std::endl;

    return 0;
}
xian
  • 4,657
  • 5
  • 34
  • 38