1

I want to create a 2D array like the following.

char **dog = new char[480][640];

But it errors:

error C2440: 'initializing' : cannot convert from 'char (*)[640]' to 'char ** '
        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

what do I need to do using "new"? (not using calloc, malloc or char dog[480][640];)

3
  • 5
    char (*p)[640] = new char[480][640]; Note that a 2D array of T is not the same as an array of pointers to arrays of T. Oh, and rather use std::vector than raw new. Cheers & hth., Commented Dec 4, 2011 at 0:50
  • Yeah, std::vector<std::array<char, 640> > dog(480); Commented Dec 4, 2011 at 2:02
  • @Mooing Duck: that covers 640x350 and 640x480 resolutions, but it does look a bit odd to mix vector and array that way. I think I'd use just vector all the way, forget about the micro-optimization possible with array, and as an added bonus get code that works with more current compilers. Cheers, Commented Dec 4, 2011 at 2:32

3 Answers 3

6

Something like this:

char **dog = new char *[480];
for (int i = 0; i < 480; i++)
    dog[i] = new char[640];

And the same when deleting, but then the loop first.

5

If you want to get memory from heap, you can use it this way:

// declaration
char *dog = new char[640*480];

// usage
dog[first_index * 640 + second_index] = 'a';

// deletion
delete[] dog;
3
  • I think an indexing scheme like this is almost always preferable to handling 2d arrays directly.
    – pg1989
    Commented Dec 4, 2011 at 0:52
  • how much more overhead is there in a 2D array vs 1D array? does it slow things down?
    – jdl
    Commented Dec 4, 2011 at 0:57
  • @jdl: shouldn't be any overhead, but this is faster for some things, and more error-prone in others. Commented Dec 4, 2011 at 2:03
0

You're creating a pointer to a pointer by using **. I'm not sure you want that, you probably want a normal pointer (*).

Not the answer you're looking for? Browse other questions tagged or ask your own question.