How to assign array of pointers

I have a 2D array:
unsigned char** x = nullptr;

I first assign the column vector like this:
x = new unsigned char*[height]

then use a loop to assign the rows like this:
for(int i=0; i<width; i++)
x[i] = new unsigned char[width]

I think this is the standard way to do it. My question is, what is the different between:
x = new unsigned char*[height]
and
x = new (unsigned char*)[height]

??


In my case, the new unsigned char*[height] returns a ** as expected but the new (unsigned char*)[height] returns *. Why is that?????
you are filling it in from the top down.

at the top you store the whole big mess as char **, which can be either a 2-d construct of char or a 1-d construct of c-strings depending on what you are doing here. I am going to assume the former here from your variable name choices.

then you go into that, to one location, and allocate a 1-d array of char.

now you can get to x[h][w] to get to a single character -- x is char **, x[h] is char *, and x[h][w] is one char.

I really dislike this, though its a standard construct and oft-used. I prefer to allocate
char*x = new unsigned char[width*height];
It is easier to new and delete this. It allows you to change width and height if you pre-allocate all you need up front and grow to fit, if that is applicable to your code (for example, transpose, where w and h reverse but allocated size is the same). You can memset or memcpy it easier. It is a single block of memory, rather than scattered across pages (which can happen with the ** approach, each new of the inside pointers can land in different pages, killing performance). Just a few of the reasons I go this route. Though now, of course, I use vector<>... of preallocated W*H instead of vector<vector<... format.






> new (unsigned char*)[height] returns ...

This is an erroneous construct; any decent compiler should emit an error diagnostic for this.
http://coliru.stacked-crooked.com/a/1cc5e3734714e95b
http://rextester.com/SXCFI55529


> I think this is the standard way to do it.

Assuming that height and width are not constants known at compile-time, the standard way is:

std::vector< std::vector< unsigned char > > x( height, std::vector< unsigned char >(width) ) ;
Topic archived. No new replies allowed.