Error for dynamic 2d array

thanks
Last edited on
a = new int[limit];[limit]

This is wrong.

You can't create a straight 2D array dynamically in C++. The closest you can get is a pointer-to-pointer style 2D array:

1
2
3
4
5
6
7
8
9
10
11
12
int** a;  // note:  int**  not int*

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

// you can now use a[r][c]

//don't forget to clean up:
for(int i = 0; i < limit; ++i)
  delete[] a[i];
delete[] a;


But as you can see, it's ugly. And the manual cleanup is easy to forget. (forgetting cleanup = memory leak)

A better solution would be to avoid doing the dynamic allocation manually... and instead use a container class like vector:

1
2
3
4
5
6
7
8
9
#include <vector>

...

std::vector< std::vector<int> > a( limit, limit );

// can now use a[r][c]

// no need to clean up... vector does it automatically. 
Last edited on
thanks
Last edited on
for this question

i need to create a 2d dynamic array that

if
cin>>limit;

a[limit][limit];

just want to get this concept..
You're defining a twice:

1
2
3
	int** a;
...
	vector<::vector<int>>a( limit, limit );


Pick one.
Topic archived. No new replies allowed.