c 裡在堆上分配和使用多維陣列的最佳方法是什麼?

時間 2021-05-30 00:45:36

1樓:你知道的

//on stack

template

size_tI,

size_t

...J

>struct

MultiDimArray

;template

size_t

I>struct

MultiDimArray

;int

main

()//on heap

namespace

details

;template

Tag>

using

type

=typename

Tag::

type

;template

size_t

n>struct

n_dim_vec

:tag

vector

>>>{};template

T>struct

n_dim_vec

:

tag<

T>{};template

size_t

n>using

n_dim_vec_t

=type

>;template

classR=

std::

vector

>Rmake_vector

(size_t

size

)template

class

...Args

,classR=

n_dim_vec_t

...(

Args)+

1>>Rmake_vector

(size_t

top,

Args

...args)}

template

class

...Args

,classR=

details

::n_dim_vec_t

...(

Args

)>>Rmake_vector

(Args

...args

)int

main()

2樓:暮無井見鈴

這裡確實是把 VLA 引入 C++ 的擴充套件。 int(*)[b][c] 是可變修改型別。

C 這麼做似乎沒什麼問題,因為 malloc 出來的記憶體一開始是沒有型別的,實際讀寫後才有有效型別。

C++ 中用 new 的話可能有 type aliasing 的問題。但由於涉及擴充套件,不排除有的情況下行為是良定義的。

C++ 中可以考慮用 gsl::multi_span ,也許未來這東西會進入標準。

c 和c語言中不用專門的動態儲存分配函式就不能實現動態儲存分配了嗎?

魚叉 好像只有gcc可以,cpp標準裡沒這回事。這種還是分在棧空間,不擴棧的話一般就幾M大小,malloc在堆裡可以更大,具體可以查查linux記憶體布局。要是這樣動態分配很容易棧不夠然後core.危險行為,常量長度棧不夠一般編譯期就會報出來。 我在devc 裡試了先定義乙個整型a,然後對a輸入值,...

c 在宣告結構指標變數的時候,會分配記憶體嗎?

瀉藥!函式clone沒有在堆上動態分配記憶體。struct S const structS clone structS R const structS bar structS R 生成中間表示式 struct.S type define arm aapcscc dereferenceable 1 s...

C語言裡,main 函式中 return x和 exit x 到底有什麼區別

AutherM exit 是乙個 system call,表示要結束這個process,不管是parent 還是child return 是乙個函式的返回,不一定結束這個process,如果出現在被main呼叫的函式中,那就是返回到呼叫函式接下來的一條語句繼續執行 如果return 在main中,則...