C++ 动态多维数组问题

C++ Dynamic multidimensional array problem

本文关键字:数组 问题 动态 C++      更新时间:2023-10-16

我正在开发一个2D平台游戏。一切都很好,直到我遇到一些难以解决的问题。关卡图存储在动态多尺寸数组(char **map)中。它工作正常,直到我想重新定义它

下面是代码的一部分:

Map& Map::operator=(const Map& rhs)
{
    if(width!=0||height!=0)
    {
        for(int i=0;i<width;i++)
            delete[] map[i];
        delete[] map;
    } //deleting previously created array
    height=rhs.height;
    width=rhs.width; //receiving other map's size
    map=new char* [width];
    walkmap=new unsigned char* [width];
    objmap=new char* [width];
    for(int i=0;i<width;i++)
    {
        *(map+i)=new char[height];
    } //creating new array
    for(int h=0;h<height;h++)
        for(int w=0;w<width;w++)
        {
            map[w][h]=rhs.map[w][h];
        } //receiving new values
    //...
}

第一次一切正常,但是当我需要第二次重新定义数组时,我的程序在部分崩溃时,当数组从另一个部分接收新值时。可能是我错过了什么,但我找不到它!我正在寻找这个问题,但没有找到我做错了什么。请帮帮我。

与往常一样,Boost 有一个优雅且内存高效的多维数组类:

http://www.boost.org/doc/libs/1_39_0/libs/multi_array/doc/user.html

例如,要设置 10 x 20 的布尔值数组:

 
    boost::multi_array  mtaFlagMatrix(boost::extents[10][20]);
 

Then to access its elements:

 
    mtaFlagMatrix[2][6] = false; // indexes are zero-based - just like normal C arrays
     ...
    if ( mtaFlagMatrix[2][6] )
    {
       ...
    }
 

Then, you can resize the array this way (existing values are preserved):

 
typedef boost::multi_array array_type;

array_type::extent_gen extents; array_type A(extents[3][3][3]); A[0][0][0] = 4; A[2][2][2] = 5; A.resize(extents[2][3][4]); assert(A[0][0][0] == 4); // A[2][2][2] is no longer valid.

This saved me a lot of time testing for extreme cases.

Your 2d array is not freeed properly. I advise you to use the Iliffe way of allocating 2d arrays which is faster and safer to use:

char** alloc_array( int h, int w )
{
  typedef char* cptr;
  int i;
  char** m = new cptr[h];
  m[0] = new char[h*w];
  for(i=1;i<h;i++) m[i] = m[i-1]+w;
  return m;
}
void release_array(char** m)
{
  delete[] m[0];
  delete[] m;
}
int main()
{
  int r,c;
  char** tab;
  int width  = 5;
  int height = 3;
  tab = alloc_array(height, width); /* column first */
  for(r = 0;r<height;++r)
   for(c = 0;c<width;++c)
    tab[r][c] = (1+r+c);
  for(r = 0;r<height;++r)
  {
    for(c = 0;c<width;++c)
    {
      printf("%dt",tab[r][c]);
    }
    puts("");
  }
  release_array(tab);
}

这可以很容易地封装在一个整洁的 2d 数组类中,或者使用 std::vector 而不是原始分配。更喜欢这种执行 2d 数组的方式,因为它对缓存友好,样式提供 [][] 访问,并且不比多项式 1d 访问慢得多。