尽管我在stackoverflow中查找了一下这个问题,我还是不知道如何解决我的问题。我知道这是一个非常原始的问题,有很多类似问题的解决方案,但它们无助于找到解决方案。
它相当简单:
我动态地分配一个三维数组,并在每个字段中存储数字2
但是VS给了我一个访问违规。
这是我的代码:

#include <stdlib.h>
#include <stdio.h>

int main() {

    int width = 512;
    int height = 512;

    int ***colors = (int ***)malloc(width * sizeof(int **));
    for (int i = 0; i < height; ++i) {
        colors[i] = (int **)malloc(height * sizeof(int *));
        for (int j = 0; j < 3; ++j) {
            colors[i][j] = (int *)malloc(3 * sizeof(int));
        }
    }

    for (int x = 0; x < width; x++)
        for (int y = 0; y < height; y++)
            for (int z = 0; z < 3; z++)
                colors[x][y][z] = 2; //Memory Access Violation happens here

    free(colors);

    return EXIT_SUCCESS;
}

最佳答案

您与for循环的索引范围混淆了。
也就是说,您没有正确分配内存,因此在使用内存时,您将访问超出限制的内存。

for (int i = 0; i < height; ++i) {
    colors[i] = (int **)malloc(height * sizeof(int *));
    for (int j = 0; j < 3; ++j) {
        colors[i][j] = (int *)malloc(3 * sizeof(int));
    }
}

应该是
for (int i = 0; i < width; ++i) {
    colors[i] = (int **)malloc(height * sizeof(int *));
    for (int j = 0; j < height; ++j) {
        colors[i][j] = (int *)malloc(3 * sizeof(int));
    }
}

关于c - 在C中使用3D阵列时出现内存读取异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56737252/

10-11 22:50
查看更多