-3

If I declare a 2D dynamic array in C++ using the following code:

int *arr2D[2];              //allocating rows statically
for(int i=0;i<2;i++)
{
     arr2D[i]=new int[6];   //for each row, 6 columns are dynamically allocated
}

Then how should I enter and display values in this 2D dynamic array using loops? (issues with dynamic array traversal for entering and displaying values in it after its allocation)

Ammarah
  • 43
  • 10

1 Answers1

2

You should use loops to input the array and display it:

int *arr2D[2];

for(int i = 0; i < 2; i++)
    arr2D[i] = new int[6];

for(int i = 0; i < 2; i++)
    for(int j(0); j < 6; j++){
        std::cout << "arr2D[" << i << "][" << j << "]: ";
        std::cin >> arr2D[i][j];
        std::cout << std::endl;
    }

for(int i = 0; i < 2; i++)
    for(int j(0); j < 6; j++){
        std::cout << "arr2D[" << i << "][" << j << "]: "
            << arr2D[i][j] << std::endl;
    }

Finally don't forget to free up memory (Memory allocated with new must be freed up by delete):

for(i = 0; i < 2; i++)
    delete[] arr2D[i];
Raindrop7
  • 3,889
  • 3
  • 16
  • 27
  • In short, can we say whether we work with static or dynamic arrays, we can enter and display array values using same subscript notation i.e. arr2D[i][j] ?? I am asking this because some approaches assign allocated memory to a pointer variable and then use that pointer to perform array operations. – Ammarah Oct 19 '17 at 14:20
  • like this one: int *p; p = new int[10]; *p = 25; p++; //p points to the next array component *p = 35; – Ammarah Oct 19 '17 at 14:24
  • 1
    No! `p++` will increment the pointer itself. You can if you use it like this: `int* ptr = p; *p =25; p++; *p = 10; p++; ` Now as you can see `ptr` keeps track of the first element. So you can use to walk memory allocated. `p = ptr; while(p) std::cout << *p; p++;` What I recommend use indexes not `C style`: `for(int i(0); i < size; i++) std::cout << p[i];`. – Raindrop7 Oct 19 '17 at 20:02
  • 1
    Yes you use `index` to input and display array elements. Remember that `arrays` are indexed from `0` as the first element to `n - 1` as the last element. Any try to read outside this interval will cause `Undefined behavior`. – Raindrop7 Oct 19 '17 at 20:07