int **dpTable = new int* [iMatrixHeight + 1];
for (int i = 0; i < iMatrixHeight + 1; i++)
{
dpTable[i] = new int [iMatrixWidth + 1];
}
memset(dpTable, 0, (sizeof(int)) * (iMatrixHeight + 1)*(iMatrixWidth + 1));
I'm using operator new to allocate a two-dimensional array, but if I use memset to initialize the array, I got a segmentfault when I access the array later. Without the memset, it's ok.
Am I doing anything wrong? THX!
The arrays dpTable[i] do not point to contiguous memory. You have to initialize then one by one
for (int i = 0; i < iMatrixHeight + 1; i++)
{
dpTable[i] = new int [iMatrixWidth + 1];
memset(dpTable[i], 0, (iMatrixWidth + 1) * sizeof(int)) ;
}
Instead of this code:
int **dpTable = new int* [iMatrixHeight + 1];
for (int i = 0; i < iMatrixHeight + 1; i++)
{
dpTable[i] = new int [iMatrixWidth + 1];
}
memset(dpTable, 0, (sizeof(int)) * (iMatrixHeight + 1)*(iMatrixWidth + 1));
… you can do this:
int **dpTable = new int* [iMatrixHeight + 1];
for (int i = 0; i < iMatrixHeight + 1; i++)
{
dpTable[i] = new int [iMatrixWidth + 1]();
}
Look ma, no memset
– instead asking for zeroing of the memory.
Still that's very ugly in C++.
So, do this:
vector<vector<int>> table( iMatrixHeight + 1, vector<int>( iMatrixWidth + 1 ) );
where vector
is std::vector
.
Or, consider defining a matrix class with just a single vector
as backing store.
Or just use an existing matrix class, eg from Boost.
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.