Search code examples
c++multidimensional-arraysegmentation-faultdynamic-memory-allocation

Accessing a 3D array in C++


I have a char*** and I dynamically allocate some memory to it. However, when I try to assign some values to it, I get segmentation fault. The size I am using is not too big. It works when I create char[768][1024][3] but doesn't work when I add this dynamically with same exact values. Here is a snippet of my code:

pic = new char**[height];
    for(int i = 0; i < height; i++)
    {
        pic[i] == new char*[width];
        for(int j = 0; j< width; j++)
        {
            pic[i][j] == new char[3];
        }
    }
    pic[0][0][0] = 'a';//seg fault here
    exit(1);

Solution

  • pic[i] == new char*[width]; -> Why is there a == comparison instead of = assignment ?

    Similarly for pic[i][j] == new char[3]; -> a comparison is being done and no assignment.