0

MyClass.hxx

class MyClass{
private:
    int ** myArray;

};

MyClass.cxx

void MyClass::setArray()
{
   int arraySize = 10;
   myArray = new int*[arraySize]

   for (int i = 0; i < 2; ++i) {
        myArray[i] = new int[arraySize]
   }

}

My question is, does this code create a 2D array constrained in one direction to two items, and constrained in the other by arraySize, similar to:

int const exampleArray[][2]{
{ 1 , 1 }
{ 1 , 1 }
{ ... , ... }
} 

I currently am able to write to the array after created (the first way) but have "undefined" behaviour about how far into the array I can write.

So my question is, what is the MyClass code doing, and how do I get the desired effect?

GPPK
  • 6,546
  • 4
  • 32
  • 57
  • 1
    Use vector it will be easier – Gilad Jan 27 '15 at 08:31
  • Please see this link on how to allow the data to be contiguous (if that is what you're asking). http://stackoverflow.com/questions/21943621/how-to-create-a-contiguous-2d-array-in-c/21944048#21944048 – PaulMcKenzie Jan 27 '15 at 09:14

2 Answers2

2

does this code create a 2D array constrained in one direction to two items, and constrained in the other by arraySize?

No. It allocates a length arraySize array of pointers. The first two pointers point to the first element of dynamically allocated arrays of length leapSecondSize. The rest of the pointers are uninitialized.

Besides the dynamic initialization, there is an important difference wrt. a 2D array: an array of pointers can be made to look like a 2D array in that each pointer can point to the beginning of a 1D array. But the data are not in a contiguous block, and there is no restriction that the pointers point at an element of an array: they can be null, they can point to a single object, they can even be uninitialized.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

That depends on what you mean by a "2D array".

If you mean the normal concept of an array of arrays, such as

int array[10][2];

then the answer is "no". If you mean that the notation

myArray[3][2] = 42;

will work, then the answer is a caveated yes. This is simply imitating the behaviour of an array of arrays, assuming the two levels of memory allocation are done correctly. The caveat is that the actual memory is laid out differently than a true array of arrays.

There is a wrinkle that the array dimensions don't match. myArray in your code is dynamically allocated as an array of 10 pointers to int. The loop only sets the first two pointers (myArray[0] and myArray[1]) to be (dynamically allocated) arrays of int. Any attempt to use myArray[3] will give undefined behaviour, since myArray[3] through to myArray[9] are not initialised.

It is also not generally possible to initialise a pointer to pointer using array initialisers (e.g. your exampleArray). It is possible to copy data across, if you have done the allocations appropriately - which you haven't.

Rob
  • 1,966
  • 9
  • 13