简体   繁体   中英

How to initialize a multi-dimensional array in a C++ constructor

I have a class that contains a few multi-dimensional arrays. I am trying to initialize these arrays in the constructor, but I am having trouble figuring our how to do it. The array is always of a fixed size. Here's what I have so far:

class foo {
  private: 
    int* matrix; //a 10x10 array

  public:
    foo();

  foo:foo() {
    matrix = new int[10][10]; //throws error
  }

the error I get is:

cannot convert `int (*)[10]' to `int*' in assignment 

how can I accomplish this? preferably, I would like the array to default to a 10x10 array of all 0s.

#include <memory.h>
class foo
{
    public:
        foo()
        {
            memset(&matrix, 100*sizeof(int), 0);
        }
    private:
        int matrix[10][10];
};

That is, if you're not binding yourself to doing it with pointers (otherwise you can just pass in the pointer to memset, rather than a reference to the array).

Do this:

int **matrix; //note two '**'

//allocation
matrix = new int*[row]; //in your case, row = 10. also note single '*'
for(int i = 0 ; i < row ; ++i)
   matrix[i] = new int[col]; //in your case, col = 10


 //deallocation
 for(int i = 0 ; i < row ; ++i)
   delete [] matrix[i];
 delete matrix;

Advice: instead of using int** , you can using std::vector as:

 std::vector<std::vector<int> > matrix;

//then in the constructor initialization list
foo() : matrix(10, std::vector<int>(10))
{  // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this is called initialization list
}

If you follow this approach, you don't need to use new and delete in your code. Also, the size of matrix is 10x10 ; you can access them as matrix[i][j] where 0<=i<10 and 0<=j<10 ; also note that all the elements in the matrix is initialized with 0 .

Try this:

class foo
{
private:
  int **matrix;

public:
  foo()
  {
    matrix = new int*[10];
    for (size_t i=0; i<10; ++i) 
      matrix[i] = new int[10];
  }

  virtual ~foo()
  {
    for (size_t i=0; i<10; ++i)
      delete[] matrix[i];
    delete[] matrix;
  }
};

Until your compiler supports C++0x uniform intialization, I'm afraid you'll have to initialize each entry in the array separately if you want to do so in the initialization list.

What you can do however, is to not initialize but assign to the array inside your constructor (simple for loop).

In your code you have a pointer, not an array. It looks like you may want to use std::vector if you need a collection of elements that takes care of memory management for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM