How to new a two-dimension array of int

L

Larry Lindsey

Wonder said:
For compiler g++ on Linux, it doesn't work if I use

int **data = new int[m][n];

Can I new an array of int* first, and new an one-dimension array for the
first int*,
then use a loop to make every int* point to the right position?

int **data = new int*[m];
data[0] = new int[m*n];
for(i = 1; i < m; i++)
data = data[0] + i * n;

It should works, however, it failed in my MPI program.
Could anyone give me a better method? Thanks.



Use pointers. C++ requires you to instantiate arrays with const values. So
instead:
int **data = (int**)malloc(m*sizeof(int*));
for (i=0;i<m;i++)
(*data+i)=(int*)malloc(n*sizeof(int));

That would be my take. This will work, but there will probably be better
ways of doing it.

--Larry
 
W

Wonder

For compiler g++ on Linux, it doesn't work if I use

int **data = new int[m][n];

Can I new an array of int* first, and new an one-dimension array for the
first int*,
then use a loop to make every int* point to the right position?

int **data = new int*[m];
data[0] = new int[m*n];
for(i = 1; i < m; i++)
data = data[0] + i * n;

It should works, however, it failed in my MPI program.
Could anyone give me a better method? Thanks.
 
R

Ron Natalie

Wonder said:
For compiler g++ on Linux, it doesn't work if I use

int **data = new int[m][n];

Because the type of new int[m][n] is not int**.
POINTERS ARE NOT THE SAME AS ARRAYS.
Can I new an array of int* first, and new an one-dimension array for the
first int*,
then use a loop to make every int* point to the right position?

int **data = new int*[m];
data[0] = new int[m*n];
for(i = 1; i < m; i++)
data = data[0] + i * n;


This looks like it should have worked to me. What happened?
 
R

Ron Natalie

Use pointers. C++ requires you to instantiate arrays with const values. So
instead:

He did use pointers. Why on earth are you using malloc? Your code won't
work anyhow. Presuably you meant *(data+i) or data in the lhs of the
last line.
 
L

Larry Lindsey

Ron Natalie said:
Use pointers. C++ requires you to instantiate arrays with const values. So
instead:

He did use pointers. Why on earth are you using malloc? Your code won't
work anyhow. Presuably you meant *(data+i) or data in the lhs of the
last line.


Oh, yeah. Good point. I'm basically a newbie anywho.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top