2

I want to initialize values of 2-D array to 0. But it seems not to work. Can I initialize values of my **array in constructor to be 0. If yes the How. My code is.

#include <iostream>
using namespace std;

int main(){
int row, col;
cin>>row;
cin>>col;
int **array=new int*[row];
        for (int i=0; i<row; i++){
            array[i]=new int[col];
        }
            for (int i=0; i<row;i++){
                for (int j=0; j<col; j++){
                    array[i][j]={'0'};
                    cout<<array[i][j]<<" ";
                }
                cout<<endl;
            }

}

Further can someone explain if I have to replace ith elem from the array with some other element, how would I deal with memory allocation.

Terrenium
  • 93
  • 2
  • 13

3 Answers3

2

You probably want array[i][j]=0;. Why were you using the char type '0'? However, there is an easier way: array[i]=new int[col]();, just add () to value initialize each column.

There also is a better way:

std::vector<std::vector<int>> array(row, std::vector<int>(col));

For your first comment, you would need to create a new array with the new size, copy over all the data, and the delete your old 2-d array.

For your second comment, here is an example:

struct A
{
    int **array;
    A(int row, int col) : array(new int*[row])
    {
       for (int i=0; i < row; i++)
       {
          array[i]=new int[col]();
       }
    }
};

PS: You can save yourself a lot of work by using std::vector.

Jesse Good
  • 50,901
  • 14
  • 124
  • 166
1

this codes works on gcc

#include <iostream>
using namespace std;

int main(){
int row, col;
cin>>row;
cin>>col;
int **array=new int*[row];
    for (int i=0; i<row; i++){
        array[i]=new int[col];
    }
        for (int i=0; i<row;i++){
            for (int j=0; j<col; j++){
                array[i][j]=0;
                cout<<array[i][j]<<" ";
            }
            cout<<endl;
        }
}

to replace ith element of the array with some other element we can do something lyk

int *aa = new int[p];
swap(array[i], aa)

but for this to work logically correct u need to make sure that p >= size of the array array[i] is pointing to. In most of our use cases we have them equal.

imagin
  • 317
  • 3
  • 13
  • Is there any way that I can set all elem to 0 the time I am initializing a 2-D array so that I don't have to write those extra 2-for loops. I am doing this in a constructor – Terrenium Nov 28 '12 at 05:59
  • whatever way u chose it can only set all elements to 0 by iterating through all the elements.. u may try short-hands to do that.. use stl.. u may use calloc() if u specifically want them to be initialized to 0. but it will anyway endup looping through all the elements and setting them to 0 individually.. so that doesn't matter i guess – imagin Nov 28 '12 at 07:06
0

You can try something like this:-

class A
{
 public:
 A():my2DArray() {0}
 private:
 B* my2DArray[max1][max2];
 };
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331