假設我有INT ****ptr;
。我想在這個ptr的末尾分配一個動態的一維數組,所以當我輸入***ptr[4]
時,我會產生一個元素。請幫忙。在quadriple指針數組分配
p.s. 我沒有在我的真實應用程序中使用此代碼,只是理解指針如何工作的知識練習。 我不能直接做***ptr = malloc(sizeof(int)*size_of_arr));
對不對?因爲這樣一來,我將不能夠產生任何元素
假設我有INT ****ptr;
。我想在這個ptr的末尾分配一個動態的一維數組,所以當我輸入***ptr[4]
時,我會產生一個元素。請幫忙。在quadriple指針數組分配
p.s. 我沒有在我的真實應用程序中使用此代碼,只是理解指針如何工作的知識練習。 我不能直接做***ptr = malloc(sizeof(int)*size_of_arr));
對不對?因爲這樣一來,我將不能夠產生任何元素
int ****ptr;
ptr = new int***();
*ptr = new int**();
**ptr = new int*();
***ptr = new int[size_of_arr];
//access (***ptr)[index]
delete[] ***ptr;
delete **ptr;
delete *ptr;
delete ptr;
非常感謝。最後一個問題:int ***之後的parethesis是否用於初始化?如果我不使用它們呢? –
請參閱http://stackoverflow.com/questions/5211090/not-using-parentheses-in-constructor-call-with-new-c – deviantfan
注意***ptr[4]
和(***ptr)[4]
是不同樣的事情。索引運算符([4]
)優先於解引用運算符(*
)。
int ****ptr;
ptr = new int***[5];
ptr[4] = new int**;
*ptr[4] = new int*;
**ptr[4] = new int;
***ptr[4] = 77;
delete **ptr[4];
delete *ptr[4];
delete ptr[4];
delete [] ptr;
這只是一種智力活動?如果你真的使用這樣的代碼,你幾乎肯定會走錯路。 – Beta
圓括號來拯救..你有沒有試圖加入你的代碼?也許可以將流程分解成2-3行代碼,也許使用一些本地幫助變量? –
沒有生產級別的代碼會使用這種結構。即使從學術角度來看,它的要求也很差。 –