#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?

Recommended Answers

All 7 Replies

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.

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];

In addition: don't forget to deallocate the memory ;)

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...

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.

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.