c++ - C++中的手动内存管理

标签 c++ arrays pointers memory nested-loops

<分区>

代码摘要:在 3d 数组中存储超过 1600 万个 uint8_t 作为指向这些 uint8_t 的指针。

代码有效,但为什么我使用 uint8_t 而不是 int 只节省了 4 KB。我使用 ints 运行相同的代码,它使用 330,488K,但对于 uint8_t,它使用 330,484。我知道其中大部分是指针,但不应该(假设每个 int 使用最小空间)将每 1600 万个 int 的大小从 2 字节减少到 1 字节已经节省了超过 4k???我认为它应该节省接近 16 MB 的空间,对吗?

通过“使用 int 运行相同的代码”,我确实执行了“查找并替换:uint8_t 和 int”,然后重新编译。

uint8_t**** num3d;
num3d = new uint8_t***[256];
for(int i=0;i<256;i++){
    num3d[i] = new uint8_t**[256];
    for(int j=0;j<256;j++){
        num3d[i][j] = new uint8_t*[256];
    }
}

// Initialize 
uint8_t *B;
for(int lx = 0;lx<256;lx++){
    for(int ly= 0;ly<256;ly++){
        for(int lz=0;lz<256;lz++){

            if(ly == 0 || lx == 0 || lz == 0 || ly == 255 || lx == 255 || lz == 255){ 
                B = new uint8_t(2);
                num3d[lx][ly][lz] = B;
                continue;
            }
            if(ly < 60){
                B = new uint8_t(1);
                num3d[lx][ly][lz] = B;
                continue;
            }
            B = new uint8_t(0);
            num3d[lx][ly][lz] = B;

        } // inner inner loop

    } // inner loop

} // outer loop

最佳答案

问题 1) 的答案......这个循环永远存在:

for (uint8_t i=0;i<256;i++)

事实上,uint8_t 可以表示的数字范围是 0...255。所以不要在这里使用 uint8_t!

在我看来,由于您的计算机正在分配这个循环,它最终会吃掉所有内存,因此问题 2) 没有任何意义。

关于c++ - C++中的手动内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21861324/

相关文章:

arrays - glVertexAttribPointer状态是否绑定(bind)到当前的GL_ARRAY_BUFFER?

c++ - 在不同类型的对象指针之间切换

c++ - 使用自定义模块构建 python 解释器时出现问题

c++ - ICPC : command line error: option '-openmp' not supported

c++ - 在 Windows 上编辑 HOSTS 文件

c - 访问二维数组时出现段错误

c++ - 这个 backward_warning.h #warning 来自哪里?

php - php中带有foreach语句的多数组回显

我们可以从同一个函数返回指向新静态数组的指针吗?

swift - 在 Swift 中存储指向变量的指针