三维数组c++中的访问冲突(使用malloc)
access violation in 3-dimensional array c++(using malloc)
我正在尝试制作一个三维整数数组,其中我知道列数是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
。
相关文章:
- 使用 malloc() 时出现意外大小
- 我怎样才能代替使用新的使用malloc翻译
- 是否可以使用 malloc 为类对象分配内存?
- 如何使用 Malloc 调试来检查本机内存泄漏?
- 如果普通默认构造函数不执行任何操作,为什么我们不能使用 malloc 创建平凡可构造的对象?
- 在使用malloc/new时无法编译stm32l4r5xx
- 如果我使用malloc()而不是堆栈数组,OpenGL不会渲染对象
- 何时以及为什么我们必须使用malloc?
- 在 C++ 中使用 malloc 添加数组
- 如何在python中创建等效的结构并使用malloc更改空指针的引用
- C++新运算符是否在下面使用 malloc()
- 联合查找算法(查找周期),不使用 malloc
- C 编程,动态内存无法使用Malloc和Calloc正常工作
- 使用malloc和指针替换矩阵中的向量
- 是否有理由使用 malloc 初始化构造函数中的指针
- std::unordered_map 如何释放使用 malloc 创建的结构.是否需要对地图进行 2 次查询
- 使用 malloc 获取阵列空间
- 无法调用使用 malloc/placement new 创建的类上的虚函数
- 使用 malloc 而不是 new 会导致 free():指针错误无效
- 添加使用malloc()并具有状态的TensorFlow OP