簡體   English   中英

C ++動態分配靜態大小的數組

[英]C++ dynamically allocated array of statically dimensioned arrays

我需要創建一個包含可變數量的'char [2]的結構,即2個字符的靜態數組。

我的問題是,如何為x個char [2]分配內存。

我試過這個(假設定義了int x):

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

(它不起作用)

我意識到我可以使用std :: vector <char [2]>作為容器,但我很好奇它是如何用原始指針完成的。

我是C ++的新手並且正在努力學習。

在您的代碼中,“m”的類型與“新”調用不匹配。 你想要的是:

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

m是指向2個字符數組的指針,你調用new來得到一個包含2個字符的x數組數組,並在第一個字符處指向m。

我相信以下代碼比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;
}
unsigned x=10;
typedef char A2[2];
A2 *m=new A2[x];
m[0][1]='a';
m[9][0]='b';
delete[] m;

C多維陣列(其中除了第一維之外的所有維度都是恆定的)是連續布局的。

如果你想要一個(可能是鋸齒狀的)多維數組,它是1d數組的1d數組,那么你必須循環:

  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;

您最終將確定數組的大小,然后使用new,並將其視為二維數組。

但是,有關此問題的詳細討論,您可能需要查看: http//www.velocityreviews.com/forums/t283481-dynamic-multidimensional-arrays.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM