想知道如何定义动态的一维二维数组?
一维二维的int数组如何定义?
一维二维的char数组如何定义?
比如:一个类的构造函数有x,y两个int参数,如何根据这两个参数动态构成数组
cls1::cls1(int x,int y)
{
   int/char mp[x][y];
   ...
}

解决方案 »

  1.   

    C的经典做法是定义一个struct,struct最后一个成员为只有一个元素的char数组,然后malloc(sizeof struct + 需要的空间)
      

  2.   

    如果是int呢?而且一维的char好象不用那么麻烦呀,有源码吗?
      

  3.   

    cls1::cls1(int x,int y)
    {
       int/char *m_pBuf=new int/char [x*y];
       int m_x=x;
       int m_y=y;
       ...
    }
    访问的时候需要自己转换一下下标
    query(int x,int y){
    return m_pBuf[x*m_y+y];
    }
    大概就是这样子吧
      

  4.   

    Class CInt1
    {
    CArray<int,int> iArray1;
    CArray<int,int>* GetArrPoint();
    }
    Class CInt2
    {
    CArray<CInt1,CInt1> iArray2;
    }
      

  5.   

    用iso c++的最好
    #include <vector>
    using namespace std;void main()
    {
      vector<char> ca;
      vector<int> ia;
      for(int i = 0; i < 10; i++)
      {
          ca.push_back(rand());
          ia.push_back(rand());  }  for(int j = 0; j < 10; j++)
            cout << ca[j] << ',' << ia[j] << endl;
    }
      

  6.   

    二维vector<vector<char> > c2a;c2a.push_back(vector<char>());
    c2a[0].push_back('a');
    cout << c2a[0][0];vector<vector<int> > i2a;
    同上
    注意vector<vector<int> 和>之间有空格
    vector<vector<int>  >
      

  7.   

    继承CArray类.
    再自己作一些两维或多维的[]操作重载思路你自己可以想得到的
      

  8.   

    vector...而且樓主 可以看看 stl源碼剖析...
      

  9.   

    支持 3m2u(SameToYou) 的方法。
      

  10.   

    给你权威一点的答案:Q: How can I define a dynamic two-dimensional array?A: The basic idea is to use a vector<vector<T> >. Use containment to write a template class that offers the desired functionality. Following skeleton code shows how to implement and use such a class:#include <vector>template <typename T>
    class dynamic_array
    {
    public:
      dynamic_array(){};
      dynamic_array(int rows, int cols)
      {
        for(int i=0; i<rows; ++i)
        {
          data_.push_back(std::vector<T>(cols));
        }
      }
      
      // other ctors ....
      std::vector<T> & operator[](int i) { return data_[i]; }  const std::vector<T> & operator[] (int i) const { return data_[i]; }  // other accessors, like at() ...  // other member functions, like reserve()....private:
      std::vector<std::vector<T> > data_;  
    };
    int main()
    {
      dynamic_array<int> a(3, 3);
      a[1][1] = 2;
      int x = a[1][1];
      return 0;
    }////////////////////////////////
    另,我自己以前也使用 <vector<vector<T> > ,也不错。