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];)

jdl
  • 6,151
  • 19
  • 83
  • 132
  • 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., – Cheers and hth. - Alf Dec 04 '11 at 00:50
  • Yeah, `std::vector > dog(480);` – Mooing Duck Dec 04 '11 at 02: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, – Cheers and hth. - Alf Dec 04 '11 at 02:32

3 Answers3

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
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;
KCH
  • 2,794
  • 2
  • 23
  • 22
0

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

Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105