Declare Pointer Options

Based on someone's instruction here, I ended up using this to declare a pointer array --

char (*chBuffer)[MAX_PATH]=new char[lrSelNum][MAX_PATH]

then I used --

1
2
delete[] chBuffer
chBuffer=0


My question is, what other ways might I have declared the pointer array. For example, would this work --

char** chBuffer=new char[lrSelNumn][MAX_PATH]

and if so, would I delete it the same way, i.e. --

1
2
delete[] chBuffer
chBuffer=0


Bascially, I would like to know some of the various ways this char array declaration could be cast, yet arriving at the exact same result.
Last edited on
*cringe*

MD arrays are code poison. Obligatory link: http://cplusplus.com/forum/articles/17108/


My question is, what other ways might I have declared the pointer array.


I'd prefer to use strings, rather than char arrays:

1
2
3
4
5
string* s = new string[lrSelNumn];

//...

delete[] s;


That way you're not limited to MAX_PATH characters (and you don't need to use MAX_PATH characters if you only need like 10 or so characters). Plus there's less (zero) risk of buffer overflows, etc, etc.

If it has to be char arrays, then I'd prefer a typedef. Something like this is MUCH more clear:

1
2
3
4
5
6
7
typedef char pathstring[MAX_PATH];

pathstring* chBuffer = new pathstring[lrSelNumn];

// 'chBuffer' is a 2D char array same as your original post

delete[] chBuffer;


For example, would this work


No. A pointer to a pointer is completely different under the hood. You could do a "nested new" approach (see previous link), but it's even more horrifying than what you're doing now:

1
2
3
4
5
6
7
8
char** chBuffer = new char*[lrSelNumn];
for(int i = 0; i < lrSelNumn; ++i)
  chBuffer[i] = new char[MAX_PATH];

// then to clean up:
for(int i = 0; i < lrSelNumn, ++i)
  delete[] chBuffer[i];
delete[] chBuffer;
Last edited on
That's what I was afraid of, i.e., the nested new. And I don't want to work with the C++ string functions. Not that there's anything wrong with them, but I want to understand why I'm doing what I'm doing.

The typedef is solution is one I've never seen with a char array. If I'm going to do something multiple times with different array names that might be a useful nugget in the future.

And I'm glad you stated it as "a pointer to a pointer" because I had forgotten that that was what that was exactly.

For now I think I'll stick with my original.
Topic archived. No new replies allowed.