0

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?

1
  • Why does not a single answer mention a 1D std::vector of dimension N*M? No stupid memory leaks. No pointers to pointers that try to represent arrays. Commented Sep 14, 2012 at 12:20

3 Answers 3

2

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];
Sign up to request clarification or add additional context in comments.

Comments

1

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])

1 Comment

You are reassigning rowptr without deleteing it's previous contents.
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.