Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I'm writing a class in C++.
I need to create a member 2d array but the size is not known until the constructor is called...Currently, in my header I have defined the array:
int* i2d;and in the constructor it's initialised:
i2d = new int[width][height];width and height are parameters passed into the constructor.
All I get with this is a compiler error 'error C2540: non-constant expression as array bound' using MSVC++6 (no MFC).
It works fine if I create it as:
i2d = new int[width * height];which will give me the same number of elements, but I really need it to be 2d...
Any ideas??
TIA

uh...
Why can't you use the latter method? That's the way people usually create 2d arrays..
You could always create a macro:
#define MAX_WIDTH 32
#define I2DMACRO(w,h) w*MAX_WIDTH+h
...
i2d[I2DMACRO(width,height)]=12345;AKhalifman@hotmail.com

#include <iostream>
using namespace std;class MyClass
{
public:
MyClass(int nRows, int nCols);
int getArray(int iRow, int iCol);
void setArray(int iRow, int iCol, int iVal);
private:
void initArray();
int **m_array;
int m_Rows;
int m_Cols;
};MyClass::MyClass(int nRows, int nCols)
{
m_Rows = nRows;
m_Cols = nCols;
initArray();
}void MyClass::initArray()
{
// dynamic allocation of 2-D arrays
int iRow;
m_array = (int **) malloc(m_Rows *sizeof(int));
for(iRow=0;iRow < m_Rows;iRow++)
m_array[iRow] = (int *) malloc(m_Cols*sizeof(int));
}int MyClass::getArray(int iRow, int iCol)
{
if (iRow>0 && iRow<m_Rows && iCol>0 && iCol<m_Cols)
return m_array[iRow][iCol];
else
return 0;
}void MyClass::setArray(int iRow, int iCol, int iVal)
{
if (iRow>0 && iRow<m_Rows && iCol>0 && iCol<m_Cols)
m_array[iRow][iCol] = iVal;
}int main()
{
int nRows = 120;
int nCols = 30;
class MyClass A(nRows, nCols);
int result;
A.setArray(30, 20, 123);
result = A.getArray(30,20);
cout << result << endl;
A.setArray(nRows-1, nCols-1, 368);
result = A.getArray(nRows-1, nCols-1);
cout << result << endl;
return 0;
}

This code may be helpful for 2d array dynamic initialization in C++
int **a;
int rows=3,cols=4;//3X4 matrix
a=new int* [rows];
for(int i=0;i<rows;i++)
*(a+i)=new int[cols];Happy Coding
Shantanu
Happy Coding
Shantanu

This code may be helpful for 2d array dynamic initialization in C++
int **a;
int rows=3,cols=4;//3X4 matrix
a=new int* [rows];
for(int i=0;i<rows;i++)
*(a+i)=new int[cols];
Happy Coding
Shantanu

![]() |
Divide Bit String
|
OS stuff
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |