Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C++ (http://www.programmingforums.org/forum15.html)
-   -   Dynamic array size (http://www.programmingforums.org/showthread.php?t=11247)

titaniumdecoy Sep 3rd, 2006 11:41 PM

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]; // ?

Why doesn't this work? How can I make it work?

grumpy Sep 4th, 2006 2:33 AM

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


Cache Sep 4th, 2006 5:36 AM

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();



All times are GMT -5. The time now is 1:01 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC