三维数组c++中的访问冲突(使用malloc)

access violation in 3-dimensional array c++(using malloc)

本文关键字:使用 malloc 访问冲突 数组 c++ 三维      更新时间:2023-10-16

我正在尝试制作一个三维整数数组,其中我知道列数是2。我正在使用malloc顺序初始化数组。请说明可能出了什么问题?

int **output_vertex[2];
for(int j=0;j<4;j++)
output_vertex[j]= (int **)malloc(sizeof(int **));
output_vertex[1][0]==(int*)malloc(2*sizeof(int));
output_vertex[1][0][0] =11;
//also tried  *output_vertex[1][0] =11;

我很难理解您的错误是什么(或者您指的是哪个)。首先,我不知道为什么要静态地创建一个数组,然后使用malloc。其次,我不明白为什么要在for循环中迭代四次(0、1、2、3)。你的分配不应该是这样的吗:

int **output_vertex;
output_vertex = (int **)malloc(2*(sizeof(int **)));

您所拥有的数组声明不是您想要的。您有一个指向int指针的两元素指针数组。本页是阅读这些声明的好指南。

就我个人而言,我更喜欢使用typedefs,并从头开始构建这样一个复杂的类型:

typedef int[2] element_type; // this is the 2-element array of ints
typedef element_type* inner_type; // this is the array of unknown size
typedef inner_type[5] outer_type; // this is the actual type we want to use
outer_type output_vertex; // we now have an array of 5 inner_type variables on the stack
// The output_vertex is *uninitialized* so we have to initialize each of its elements
for (int i=0; i < 5; ++i) {
output_vertex[i] = new inner_type[SOME_SIZE];
}
// do stuff with output_vertex now that it's initialized
// then, to prevent memory leaks, delete the memory you allocated
for (int i=0; i < 5; ++i) {
delete[] output_vertex[i];
}

可能有一些简化的方法,但这应该是一个开始。

如果您希望inner_type是可追加的,我强烈建议您使用std::vector而不是原始数组。原始数组需要进行大量的记账,所以我不举一个例子;然而,以下是您对std::vector:的大致操作

typedef std::pair<int,int> element_type; // this is the 2-element array of ints as a pair
typedef std::vector<element_type> inner_type; // dynamic vector this time
inner_type output_vertex[5]; // we now have an array of 5 inner_type variables on the stack
// do stuff with output_vertex

std::vector和动态分配的数组一样快,但您不必自己记账。您还可以不需要管理那么多堆分配的对象。

请注意,原始数组与容器(例如std::vector)不兼容,所以我在这里使用std::pair

如果您能够使用C++11(或boost),并且需要一个固定大小的数组,其中包含两个以上的项,可以放入一个标准容器中,请使用std::array