1
void playWithThePixels(void* p, int depth, int pitch, int width, int height);

typedef unsigned char Pixel[4];
std::vector<Pixel[1600]> screen(900);
playWithThePixels(screen.data(), 32, 1600, 1600, 900);
return 0;

Both the elements of a C array and std::vector is guaranteed to be contiguous, so screen should be laid out contiguously in memory.

I know accessing the array elements out of bounds is undefined behaviour, but how about when reading through a pointer, such as in the example code?

Or what if you do

std::cout << screen[0][10000][0];

? Is this defined behaviour? I'm obviously accessing an allocated area.

Does reading the array elements whether directly or indirectly through a pointer make a difference?

  • 2
    The program is ill-formed: the `vector` type parameter must not be an array type (e.g. because of allocator requirements). – Kerrek SB Jul 06 '15 at 07:35
  • @KerrekSB Okay then let me swap the vector to `std::array` or a plain array or a pointer to array. –  Jul 06 '15 at 07:37
  • 2
    The general rules are: 1) Don't access arrays out of bounds. 2) No type punning. Basically, what you're thinking is not allowed. – Kerrek SB Jul 06 '15 at 07:38
  • I very much want to close this as a dupe of [One-dimensional access to a multidimensional array: well-defined C?](http://stackoverflow.com/q/6290956/183120) but people will nit on the tag difference; however in this context, the languages mandate the same behaviour. – legends2k Jul 06 '15 at 11:42

1 Answers1

0

Yes, it should work. For the only reason that the size of Pixel[1600] will fit the alignment conditions for most CPU architectures.

Usually, in image processing it is easiest to put an image in a one-dimensional array and do the calculations for accessing a pixel manually or by help of a corresponding class that encapsulates the access.

For example in your case the index calculation would be:

int pixelIdx = column + row * rowSize;

where rowSize would be 1600 in your case. In most scenarios the width and height of your images is not known at compile time and therefore you have to resort to that strategy anyway.

nv3
  • 400
  • 4
  • 9
  • 1
    This is wrong. There's only one `vector`, you seem to be arguing against a `vector>`. In practice, the OP example will work (using `std::array`, at least), but it violates the strict rules of the standard. – Potatoswatter Jul 06 '15 at 09:17
  • You are absolutely right. I am going to update my post. Thanks for the hint. – nv3 Jul 06 '15 at 11:35