c++ - Convert malloc to new -
how write following code using new operator? please explain in detail. in advance.
#include<alloc> #define maxrow 3 #define maxcol 5 using namespace std; int main() { int (*p)[maxcol]; p = (int(*)[maxcol])malloc(maxrow*sizeof(*p)); }
quite simply, answer question literally:
p = new int[maxrow][maxcol];
this allocates 2d array (maxrow maxcol) on free store and, usual new
, returns int(*)[maxcol]
- same type decaying 2d array. don't forget delete[] p;
.
the last part brings importance of std::vector
. presumably, know size of second dimension @ compile-time. therefore, std::vector<std::array<int, maxcol>>
work added bonus of not requiring delete[]
statement, plus knows size (maxrow). please use if @ possible.
in fact, in example, both dimensions known @ compile-time, meaning std::array<std::array<int, maxcol>, maxrow>
work here. that's typically preferable dynamic allocation.
if neither dimension known @ compile-time, best bet vector of vectors or dedicated matrix class increase performance when know every inner vector same size.
Comments
Post a Comment