collapse when using new[] to create arrays

I am trying to create a two-dimensional arrays as follows:

int index=0;
int dimension1=4;
int dimension2=10;
int **arr;
arr=new int* [dimension1];
for(index=0;index<dimension1;index++)
{
arr[index]=new int[dimension2];
}
for(int i=0;i< dimension1;i++)
{
for(int j=0;j< dimension2;j++)
{

arr[i][j]=i*dimension2+j;
printf("%d, ",arr[i][j]);
}
printf("\n");
}


when running the code above,the program just collapse,my system is windows7,and I am using visual c++6.0;

then ,I change 'dimension1' to 3, it just works fine,and so with less than 3
why not this?

int array [1000] [1000]
a 2D array will be contiguous in memory which int **arr will not be, as it is an array of pointers, not an array of arrays.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

const int rows = 5; // 
const int cols = 5; // this must be a constant

int main()
{

  int(*array)[cols] = new int[rows][cols];
  int count = 0;
  for(int r = 0; r < rows; r++)
    for(int c = 0; c < cols; c++)
      array[r][c] = count++;
  for(int r = 0; r < rows; r++)
    for(int c = 0; c < cols; c++)
      std::cout << "array[" << r << "][" << c << "] = " << array[r][c] << std::endl;
  delete[] array;
  return 0;
}

yes, I see this is a way of defining an 2d array,but only if the rows and cols are constant.
but ,I want a 2d array whose rows and cols are calculated by functions,that is they are not constants.

for example there is a string like "adsas asda sdf asd sfr", which was divided by ' '. and I want to split the string by ' '. through using strtok(),I can get all the substrs. but I need them stored in an array. so I refer to 2d dynamic array. and I followed a tutorial which ask me to do like that.

so is there any indea, or where to find the related tutorial
closed account (D80DSL3A)
Your code looks fine. I tested it myself and found no problems regardless of the value of dimension1 ( including dimension1 = 3 ).

The problem must lie elsewhere.

OK. One problem = memory leak. Remember to delete dynamically allocated memory when you are finished with it. For your case use:
1
2
3
4
5
for(int i=0;i<dimension1;i++)
{
    delete [] arr[i];// each array of ints
}
delete [] arr;// the array of int*'s 

Failure to release this memory wouldn't cause your problem though.

EDIT: Texan40s method does allow for a dynamic (non-constant) value for rows. The cols dimension must be a constant though.
Last edited on
yes you are right , when I comment some part of my code,and it works fine even I change dimension1 to 2000;

thanks !!!
Topic archived. No new replies allowed.