![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Expert Programmer
|
Dynamic array size
I want to create a 2-dimensional array of size N by N, where N is an integer read from a file.
int N;
std::ifstream in("file.in");
in >> N;
int **array = new int[N][N]; // ? |
|
|
|
|
|
#2 |
|
Programming Guru
![]() Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,223
Rep Power: 5
![]() |
The short answer is that you can't do it, at least not in one step, because operator new [] only allocates a 1-dimensional array. A two dimensional array is an array one one dimensional arrays (more generally, an n-dimensional array is an array of (n-1) dimensional arrays.
One way of doing this is; int **array = new (int *)[N]; // array is a dynamically allocated array of pointers to int
for (int i = 0; i < N; ++i)
array[i] = new int [N]; // and each pointer in array is now a dynamically allocated array of int |
|
|
|
|
|
#3 |
|
Hobbyist
Join Date: Sep 2005
Posts: 261
Rep Power: 4
![]() |
You could use std::vector as an alternative to built in arrays. All the memory management is done for you.
typedef int element; typedef std::vector<element> row; typedef std::vector<row> two_d; int N = 10; two_d collection(N, row(N, 0)); // NxN elements initialezed to 0. collection.at(0).at(0); collection[0][0]; two_d::const_iterator td_iter = collection.begin(); row::const_iterator iter = td_iter->begin(); |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| changing size of an array | Eric the Red | Java | 3 | Apr 3rd, 2006 8:19 PM |
| dynamic union array doesn't work | Mathsniper | C | 13 | Nov 21st, 2005 6:34 AM |
| Change the size of a character array dynamically? | bivhitscar | C | 23 | Nov 5th, 2005 5:55 AM |
| How to say the size of an array using printf ? | colt | C | 2 | May 19th, 2005 3:25 PM |
| Installing IPB 2.03 | bh4575 | Other Web Development Languages | 0 | Apr 23rd, 2005 2:36 AM |