-5

Suppose I have int ****ptr;. I want to allocate a dynamic 1-dimensional array on the end of this ptr, so when I type ***ptr[4] I would yield an element. Please, help.

p.s. I am not using this code in my real applications, it's just an intellectual exercise to understand how pointers work. I cannot directly do ***ptr = malloc(sizeof(int)*size_of_arr)); right? BEcause this way i will not be able to yield any elements

John Doe
  • 7
  • 2

2 Answers2

1
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;
deviantfan
  • 11,268
  • 3
  • 32
  • 49
  • thank you very much. One last question: parethesis after int*** are used for initialization? What if I don't use them? – John Doe Sep 30 '15 at 23:04
  • See http://stackoverflow.com/questions/5211090/not-using-parentheses-in-constructor-call-with-new-c – deviantfan Sep 30 '15 at 23:06
0

Note that ***ptr[4] and (***ptr)[4] are not the same thing. The index operator ([4]) takes precedence over the dereference operator (*).

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
  • 96,650
  • 16
  • 149
  • 150