Reputation: 1187
I saw somewhere the following code and I am little bit confused.
int**** m_ppppCoder;
m_ppppCoder = new int ***[10];
Is that a 3 dimensional int array that allocated dynamically ? Can someone explain exactly, how it works ?
Added after reading the comments: The declaration above by itself, is not a complete 3d int array but the declaration structure with the 1st step of the array creation. According to this, with the following code below, You can create dynamically a 3d array. Is that correct ?
m_ppppCoder[0] = new int **[10];
m_ppppCoder[0][0] = new int *[10];
m_ppppCoder[0][0][0] = new int[10];
In this case, the actual data how are arranged (allocated) inside the memory ie sequentially ?
Upvotes: 3
Views: 3986
Reputation: 238421
Is that a 3 dimensional int array that allocated dynamically ?
No.
int**** m_ppppCoder
m_ppppCoder
is a pointer to a pointer to a pointer to a pointer to an integer.
m_ppppCoder = new int * **[10];
m_ppppCoder
points to the first element of a dynamically allocated array of 10 pointers to a pointer to a pointer to an integer.
Can someone explain exactly, how it works ?
Well, it's a pointer to an element of an array, so it doesn't do much of any work by itself. An example of usage:
int i = 42; // an integer i
int *ii = &i; // ii points to i
int **iii = ⅈ // iii points to ii
m_ppppCoder[0] = &iii; // the first element points to iii
int j = ****m_ppppCoder[0]; // the value of j is now 42
delete[] m_ppppCoder; // never forget to delete dynamic memory
There is probably no good practical use for an int****
.
m_ppppCoder = new int ***[10]; m_ppppCoder[0] = new int **[10]; m_ppppCoder[0][0] = new int *[10]; m_ppppCoder[0][0][0] = new int[10];
In this case, the actual data how are arranged (allocated) inside the memory ie sequentially ?
Like this:
pointer to int*** p
|
an array of 10 int*** |->[0][1][2][3]...
|
an array of 10 int** |->[0][1][2][3]...
|
an array of 10 int* |-> [0][1][2][3]...
|
an array of 10 int |-> [0][1][2][3]...
It's quite simple. You have allocated 4 arrays. Since they are separate allocations, each of those 4 arrays are separate from each other, somewhere in the free store.
Elements of an array themselves are consecutive in memory. Therefore each of the pointers (or integers in the case of the last one) are consecutive in the memory in relation to other elements of the same array.
Note that m_ppppCoder[x]
, m_ppppCoder[0][x]
and m_ppppCoder[0][0][x]
are uninitialized pointers for all x in [1, 10).
Upvotes: 9