代码之家  ›  专栏  ›  技术社区  ›  ejm Xan

C++动态分配静态数组数组

  •  2
  • ejm Xan  · 技术社区  · 15 年前

    我需要创建一个结构,它包含一个可变数量的“char[2]”,即2个字符的静态数组。

    我的问题是,如何为x个字符分配内存[2]。

    我尝试过(假设定义了int x):

    char** m = NULL;
    m = new char[x][2];
    ...
    delete [] m;
    

    (不起作用)

    我知道我可以使用std::vector<char[2]作为容器,但我很好奇如何使用原始指针。

    我是非常新的C++和努力学习。

    4 回复  |  直到 15 年前
        1
  •  4
  •   Chris Dodd    15 年前

    在代码中,“m”的类型与“new”调用不匹配。你想要的是:

    char (*m)[2] = NULL;
    m = new char[x][2];
    ...
    delete [] m;
    

    m是指向2个字符数组的指针,您调用new得到一个2个字符的x数组,并在第一个字符处指向m。

        2
  •  4
  •   Kirill V. Lyadvinsky    15 年前

    我相信下面的代码比 char[n][2] :

    typedef char wchar[2];   // array of two chars
    const size_t n = 100;    // some const
    wchar* x = new wchar[n]; // array of wchars, where wchar is array of two chars
    
    // here is still a problem that you could write the following
    x[5][5] = 0;             // not what you expected?
    
    delete[] x;              // clean up
    

    如果我们知道wchar的内部结构,那么如果我们声明它如下,代码将更加可读:

    // using struct is just gives names to chars in wchar, without performance drop
    struct wchar {
      char h;
      char l;
    };
    
    ...
    
    const size_t n = 100;    // some const
    wchar* x = new wchar[n]; // array of wchars
    
    x[0].h = 0;
    x[0].l = 0;
    
    delete[] x;              // clean up
    

    最后,因为我们使用C++,不需要使用C数组:

    const size_t n = 100;    // some const   
    typedef std::tr1::array<wchar, n> my_arr;
    my_arr* x = new my_arr;
    
    (*x)[0].h = 0;
    (*x)[0].l = 0;
    
    delete x;
    

    另一个非常安全的选项是编译时间范围检查:

    template<int n_max>
    struct array_n {
        char v[2*n_max];
    
        template<size_t n, size_t s> 
        char& get() {
            BOOST_STATIC_ASSERT( s < 2 );
            BOOST_STATIC_ASSERT( n < n_max );
            return v[n*2+s];
        };  
    };
    
    int main( int argc, char**argv)
    {
        const size_t n = 100;    // some const   
        typedef array_n<100> my_arr;
        my_arr* x = new my_arr;
    
        x->get<10, 1>() = 0;   // ok
        x->get<50, 0>() = 0;   // ok
        x->get<10, 2>() = 0;   // compile time error
        x->get<500, 0>() = 0;  // compile time error
    
        delete x;
    }
    
        3
  •  0
  •   James Black    15 年前

    您将最终确定数组的大小,然后使用new,并将其视为二维数组。

    但是,为了更好地讨论这一点,您可能希望看到: http://www.velocityreviews.com/forums/t283481-dynamic-multidimensional-arrays.html

        4
  •  0
  •   Jonathan Graehl    15 年前
    unsigned x=10;
    typedef char A2[2];
    A2 *m=new A2[x];
    m[0][1]='a';
    m[9][0]='b';
    delete[] m;
    

    c多维数组(除第一个维度外的所有维度都是常量)是连续排列的。

    如果您想要一个(可能是锯齿状的)多维数组,它是一维数组的一维数组,那么您必须循环:

      char **m=new char *[x];
      for (unsigned i=0;i<x;++i) m[i]=new char[2];
      ...
      for (unsigned i=0;i<x;++i) delete[] m[i];
      delete[] m;