Zuhair Taha
Zuhair Taha

Reputation: 3032

cpp two dimensional dynamic array

I'm using c++ and I want to use two dimensional dynamic array. I tried this:

#include<iostream.h>
using namespace std;
void main(){
int const w=2;
int size;
cout<<"enter number of vertex:\n";
cin>>size;
int a[size][w];
for(int i=0; i<size; i++)
   for(int j=0; j<w; j++){
      cin>>a[i][j];
  }

}

but not worded. and I tried this:

int *a = new a[size][w];

instead of

int a[size][w];

but not worked!

could you help me plz.

thanks a lot.

Upvotes: 0

Views: 1498

Answers (4)

The correct approach here would be to encapsulate some of the standard containers, that will manage memory for you, inside a class that provides a good interface. The common approach there would be an overload of operator() taking two arguments that determine the row and column in the matrix.

That aside, what you are trying to create manually is an array of dynamic size of arrays of constant size 2. With the aid of typedef you can write that in a simple to understand manner:

const int w = 2;
typedef int array2int[w];
int size = some_dynamic_value();
array2int *p = new array2int[size];

Without the typedef, the syntax is a bit more convoluted, but doable:

int (*p)[w] = new int [size][w];

In both cases you would release memory with the same simple statement:

delete [] p;

The difference with the approaches doing double pointers (int **) is that the memory layout of the array is really that of an array of two dimensions, rather than a jump table into multiple separately allocated unidimensional arrays, providing better locality of data. The number of allocations is lower: one allocation vs. size + 1 allocations, reducing the memory fragmentation. It also reduces the potential from memory leaks (a single pointer is allocated, either you leak everything or you don't leak at all).

Upvotes: 4

Brandon
Brandon

Reputation: 23498

OP is saying he wants to create a 2 dimensional array where one dimension is already known and constant and the other dimension is dynamic.. Not sure if I got it right but here goes:

int main() {
    const int w = 2;

    int size = 10;

    int* arr[w];

    for (int i = 0; i < w; ++i)
        arr[i] = new int[size];


    //do whatever with arr..
    //std::cout<<arr[0][0];

    for (int i = 0; i < w; ++i)
        for (int j = 0; j < size; ++j)
            std::cout<<arr[i][j];


    for (int i = 0; i < w; ++i)
        delete[] arr[i];

    return 0;
}

Upvotes: 1

user1708860
user1708860

Reputation: 1753

You can not do that in c++, please read about dynamic memory allocation

the code below should work

int* twoDimentionalArray = new [size*w]

Upvotes: 1

dornhege
dornhege

Reputation: 1500

For a dynamic sized array you must dynamically allocate it. Instead of

int *a = new a[size][w];

Use

int** a = new int*[size];
for(int i = 0; i < size; i++)
    a[i] = new int[w];

Upvotes: 2

Related Questions