user1583707
user1583707

Reputation: 1

Two-dimensional array initialization

CASE1:

int nrows=5;
int ncols=10;
int **rowptr;
rowptr=new int*;
for(int rows=0;rows<nrows;rows++) {
  for(int cols=0;cols<ncols;cols++) {
    *rowptr=new int;
  }
}

CASE2:

int nrows=5;
int ncols=10;
int **rowptr;
for(int rows=0;rows<nrows;rows++) {
  rowptr=new int*;
  for(int cols=0;cols<ncols;cols++) {
    *rowptr=new int;
  }
}

I am able to insert and print values using both ways. What is the difference in initializations?

Upvotes: 0

Views: 454

Answers (3)

hjbabs
hjbabs

Reputation: 37

You'd better use 1d array to manage 2d array

int **x = new int*[nrows];
x[0] = new int[nrows*ncols];
for (int i = 1; i < nrows; i++)
    x[i] = x[i-1] + ncols;

for (int i = 0; i < nrows; i++)
    for (int j = 0; j < ncols; j++)
        x[i][j] = 0;

delete [] x[0];
delete [] x;

Upvotes: 0

You have a memory leak in both cases.

The proper way to initialize such a "2d" array is

int** arr = new int*[nrows];
for (int i = 0; i < nrows; i++)
   arr[i] = new int[ncols];

Note however, that it isn't a 2d array as defined by C/C++. It may not, and probably will not, be consecutive in memory. Also, the assembly code for accessing members is different.

In your case, the accessing by indexing is equivalent to *(*(arr+i)+j)

And in the case of a 2d array it's *(arr + N_COLS*i + j) when N_COLS is a compile time constant.

If you want a true 2d array you should do something like this:

int (*arr)[N_COLS] = (int(*)[N_COLS])(new int[N_ROWS * N_COLS])

Upvotes: 1

Alok Save
Alok Save

Reputation: 206518

What is the difference?

#1 just allocates memory enough to hold a integer pointer and not an array of integer pointers.
#2 Causes a memory leak by just overwritting the memory allocation of the previous iteration.

I am able to insert and print values using both the ways

Memory leaks and Undefined behaviors may not produce immediate observale erroneous results in your program but they sure are good cases of the Murphy's Law.

The correct way to do this is:

int nrows = 5;
int ncols = 10;

//Allocate enough memory for an array of integer pointers
int **rowptr = new int*[nrows]; 

//loop through the array and create the second dimension
for (int i = 0;i < nrows;i++)
    rowptr[i] = new int[ncols];

Upvotes: 2

Related Questions