Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

variable sized 2d arrays 2

Status
Not open for further replies.

DaMutation

Programmer
Dec 27, 2003
5
US
i've been trying to make a 2d array pointer with a variable size (something like int *x=new int[size] but with 2 dimensions). The closest i've gotten to this is using old C code making an array using malloc, making another array several times the size of that, and then use memcopy to get all the values in and out. As you can imagine, this is very annoying, especially since i read the entire array block several times in a function, and when accesing a specific piece of data it takes 3 lines of code just to get it!!! How can i get a dynamic 2d array where i can use the normal, everyday [][] syntax??
 
Code:
int** x;
x = new int*[size1];
for(int i = 0; i < size1 ; i++)
{
  x[i] = new int[size2];
}
//using
for(int i = 0; i < size1; i++)
{
  for(int j = 0; j < size2; j++)x[i][j] = xxx;
}


//freeing memory

for(int i = 0; i < size1 ; i++)
{
  delete[] x[i];
}
delete[] x;

Ion Filipski
1c.bmp
 
You could also use the standard template class vector:

typedef vector< vector< int > > My2DArray;

The advantages are you can still use [][] syntax, but you don't need the &quot;freeing memory&quot; part. The object takes care of its own destruction (unless instead you have it contain pointers.)
 
Thanks alot. I had just remembered the vector template right after i posted the messgae, but im having the data compressed and thrown over TCP/IP, its easier to handle it the first way, as well as faster. Thanks to both of you though.
 
There is a way to liniarize the 2D to one dimension and the code is faster depending on how many times you are using the new operator and if you are looking for performance:

// 2 Dimesions
int dim1 = 200;
int dim2 = 48;
int *ar = new int[dim1*dim2];
// Initialize
for (int i=0;i<dim1;i++)
for (int j=0;j<dim2;j++)
{
*(ar + i*dim2 +j) = 0;
}

// Access [j] value where i=0...dim1, j=0...dim2
int val = *(ar + i*dim2 + j);
// Free array
if (ar)
{
delete [] ar;
ar = NULL;
}

-obislavu-
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top