1
#include <iostream>
using namespace std;
int main()
{
    int rows = 3, columns = 3;
    int ****p;
    p = new int***();
    *p = new int**();
    **p = new int*[rows];
    for(int i = 0; i < rows; i++)
    {
       ***(p+i) = new int [columns]; //Crashed at ***(p+1) why?
    }
}

I'm trying to make this code work but the compiler keep crashing when i try to run it. I narrowed the problem to the commented line. I don't understand why?

Edited by P3C1

5
Contributors
7
Replies
8
Views
4 Years
Discussion Span
Last Post by P3C1
0

The problem is probably caused by p + 1 not being a good address for dereferencing. You've assigned p using dynamic memory allocation (new int***), so I don't know what the next int*** in memory will be. To be safe, you should probably only perform pointer arithmetic on pointers that point to arrays.

0

Why so many levels of indirection? The top two clearly aren't necessary within this program, so you could just do this:

int **p = new int*[rows];

for (int i = 0; i < rows; i++)
    p[i] = new int[columns];
0

Pointer to pointer to pointer to 2d array

Why would you need that? Can you explain a bit? Because, if you want a 2d array you should do what deceptikon suggested; perhaps you want it for a reason, one that you haven't shared...

0

Its a quiz from school to learn about levels of indirection. From what i think, somehow during the third level of interaction while allocate rows(which is 3 in example), the compiler only create 1 row instead of 3 as asked.

**p = new int*[rows];

How do i go about fixing that? Thank you for taking your time to read this guys.

0

From what i think, somehow during the third level of interaction while allocate rows(which is 3 in example), the compiler only create 1 row instead of 3 as asked.

As a student you need to learn to stop thinking that the compiler might be making a mistake. The compiler always does what it is asked to do. If there is a problem it is because the compiler is being asked to do something you don't want it to do.

In this case it wouldn't even matter if the allocation **p = new int*[rows] only allocated a pointer for one row, since only the first row is ever accessed.

1

I found the problem

***(p+i) = new int [columns];

The way i use to access rows is wrong. It should be like this

   *(**p+i) = new int[columns];

Can't believe i missed it, took me forever to notice the problem >_<. Thank you for taking your time to help me guys, appreciated it.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.