Defining an AnsiString matrix in Borland C++ builder without knowing the size -
Defining an AnsiString matrix in Borland C++ builder without knowing the size -
i have next code:
int cl = value1; int fl = value2; ansistring **mat = null; mat = (ansistring **)malloc(sizeof(ansistring)*fl); for(int i=0; < fl; i++) mat[i]=(ansistring *)malloc(sizeof(ansistring)*cl); int count = 0; (int f=0; f<fl; f++){ (int c=0; c<cl; c++){ if (count < str.length()) mat[f][c]=str[++count]; else mat[f][c]='x'; } }
but not working. read several "how to's" can't find right way it.
i'm pretty noob malloc thing advice/help apreciated.
thank much in advance.
never allocate non-pod objects using malloc, are:
mat[i]=(ansistring *)malloc(sizeof(ansistring)*cl)
the constructor of object won't called (you have phone call manually afterwards using placement new operator). line above pleading memory error.
use new[]
operator instead:
ansistring **mat = mat = new ansistring*[fl]; for(int i=0; < fl; i++) mat[i] = new ansistring[cl];
you can still access object using mat[m][n]
, m
row number , n
column number.
don't forget free memory using delete[]
when done:
for(int i=0; < fl; i++) delete[] mat[i]; delete[] mat;
however, using new[]
/delete[]
still error prone if not careful. recommend utilize std::vector
instead, , allow manage of memory you:
std::vector< std::vector<ansistring> > mat( f1 ); for( = 0; < f1; ++i ) mat[i].resize( c1 );
you can still access object using mat[m][n]
, don't have worry freeing free automatically when goes out of scope.
c++ borland-c++
Comments
Post a Comment