0

I want to create a 3D array of 744 * 93 * 105. When I am running the code, I am getting Segmentation fault (core dumped). when I am keepin dimension of the array low, I am not getting any error. What is maximum number of element can I store in 3 dimensional array in c++? and How can I create a 3D array of dimensions 744 * 93 * 105?

3Dave
  • 28,657
  • 18
  • 88
  • 151
  • 2
    Perhaps you are attempting to create the array on the stack. I doubt you will have 55.4 MB of stack space available (assuming 64-bit integers as values) - usually a thread has something like 1-10 MB of stack space allocated, and that's already generous for everyday usage. Create it on the heap instead (using `new`). – CherryDT Feb 21 '22 at 18:12
  • Does this answer your question? [Segmentation fault on large array sizes](https://stackoverflow.com/questions/1847789/segmentation-fault-on-large-array-sizes) – n. m. could be an AI Feb 21 '22 at 18:29

1 Answers1

0
  • You can use std::vector for this. Elements will be stored in the heap, so your memory usage is not so restricted.
  • An std::array would look more appropriate in this case, since the dimensions of the structure seem to be fixed, but that would allocate the elements in the stack, so you would still have the current problem.
  • You can define the vector recursively using the constructor that takes the number of elements as first parameter, and a value as the second parameter; except for the innermost vector, which you can just define as having a given number of elements.

[Demo]

#include <fmt/core.h>
#include <iostream>  // cout
#include <vector>

constinit const size_t width{744};
constinit const size_t height{93};
constinit const size_t depth{105};

int main ()
{
    std::vector<std::vector<std::vector<int>>> v(
        width,
        std::vector<std::vector<int>>(
            height,
            std::vector<int>(
                depth
            )
        )
    );
    std::cout << fmt::format(
        "v.width = {}, v.height = {}, v.depth = {}",
        v.size(), v[0].size(), v[0][0].size()
    );
}
rturrado
  • 7,699
  • 6
  • 42
  • 62