2

Okay, so consider this code:

char** pool = new char*[2];
pool[0] = new char[sizeof(char)*5];

As far as I know, this creates a pointer to an array of 2 char pointers. The second line then sets the first of these 2 char pointers to the first item in an array of 5 chars. Please correct me if I'm wrong.

If I'm not wrong:

  1. How would I go about initializing all of these chars?
  2. How would I change a specific char? For example, setting the last char to NULL in each array.
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
scorkla
  • 300
  • 1
  • 9
  • for the "how" part http://stackoverflow.com/questions/12935752/how-to-memset-char-array-with-null-terminating-character – user2485710 Jan 25 '14 at 21:48

1 Answers1

2

As far as I know, this creates a pointer to an array of 2 char pointers. [...]

char** pool = new char*[2];

No, that line creates a pointer to a pointer a character. The expression on the righthand side creates an array of 2 pointers to characters. You can initialize this a double pointer with an array of pointers, because the righthand side will decay into a double pointer.

The second line then sets the first of these 2 char pointers to the first item in an array of 5 chars. [...]

pool[0] = new char[sizeof(char)*5];

What do you mean by "the first of these two char pointers". You're only assigning to one pointer on that line.

How would I go about initializing all of these chars?

By using a loop to iterate through the pointers and assigning valid memory to them.

How would I change a specific char? For example, setting the last char to NULL in each array.

for (char** p = pool; p != (pool + 2); ++p)
{
    *p = new char[/* amount of chars */];
    (*p)[/* amount of chars */] = '\0';
}

But this is a complete mess. It would be significantly more easy to use a vector of strings:

std::vector<std::string> pool;
Community
  • 1
  • 1
David G
  • 94,763
  • 41
  • 167
  • 253
  • Thank you, looks like I had quite a few things wrong. Thanks for the clarification and simplification. I agree, it's a complete mess. – scorkla Jan 31 '14 at 19:14