Friday, July 6, 2012

How to allocate a 2-Dimensional array in C/C++ using only 2 malloc calls / new operators.

Code:

#include<iostream>
using namespace std;

#define ROWSIZE 3
#define COLSIZE 4
int main()
{
int *p,**q;
p = new int[ROWSIZE*COLSIZE];
for(int i=0;i<ROWSIZE;++i)
q[i] = (int *)(p + i*COLSIZE) ;
q[1][1] = 1;
for(int i=0;i<ROWSIZE;++i)
{
for(int j=0;j<COLSIZE;++j)
std::cout<<q[i][j]<<" ";
std::cout<<std::endl;
}
return 0;
}

No comments:

Post a Comment