结构中数组的c++malloc
c++ malloc for array in struct
我是一名java编程人员,正在尝试学习一些c++,但我仍然有点不确定数组malloc和structs的交互。我有以下代码:
#include <stdlib.h>
#include <stdio.h>
struct MapData
{
double heights[];
int width;
};
void Map(int xsize,int ysize)
{
MapData md;
md.width=xsize;
md.heights=malloc(sizeof(int)*xsize*ysize);
}
我现在可以将数据存储在这个MapData结构中以备将来使用。然而,这不起作用,因为"不兼容的类型void*无法分配给double[0]。我知道这可能很愚蠢,但我已经尝试了一些方法,我认为它应该起作用。我需要安装一些东西来获得malloc吗?还是使用malloc来分配数组,这不是c++中的方法(我以前在c中写过一个小程序,它使用malloc来做类似的事情,但我记不清/找不到那个程序的代码(。
您正在寻找一个动态分配的数组。在C++中,这是std::vector<>
。所以你应该这样声明heights
:
std::vector<double> heights;
您可以使用heights.push_back(1.5);
添加项目。您也可以使用heights.resize(...)
在一次拍摄中设置尺寸
请参阅上的文档http://www.cplusplus.com/reference/vector/vector/
malloc
在C++中不受欢迎,因为它没有类型安全性,与非POD类型不兼容,并且没有针对内存泄漏的固有保护。
您可以使用new[]
(例如double* heights; ... heights = new double[n]; ... delete [] heights;
(获得类型友好性,但这仍然没有内存泄漏保护。
std::vector
是较好的选择。
您正在尝试的C++版本是:
更新:OP澄清了要求,它在逻辑上是一个2-D阵列,存储在1-D矢量中(这很好,我更喜欢这样,而不是使用矢量的矢量(
#include <vector>
struct MapData
{
int width;
std::vector<double> cells;
double &cell(int x, int y)
{
return cells.at(y * width + x);
}
MapData(int xsize, int ysize) // the constructor
: width(xsize), cells(ysize*xsize)
{ }
};
因为您的类只包含"nice"类型,所以它在复制、移动和赋值时的默认行为是正确的。
用法:
int main()
{
MapData my_data(5, 6);
my_data.cell(0, 3) = 1.1;
}
注意:我交换了元素的顺序,以便初始化列表的顺序与实际的初始化顺序匹配(初始化按照类中元素的顺序进行,而不是按照init列表的顺序进行(。
考虑将cells
和width
设为私有,以避免地图用户意外直接访问它们。
在C或C++中处理此问题的方式存在一些差异。你必须选择一个。
在C中,您需要malloc
和家人。请确保实际使用的是C编译器,而不是C++编译器。
double (*my_array)[ysize]; // Pointer to your new two-dimenasional array with column size ysize
my_array = calloc(sizeof(double), xsize*ysize); // allocates memory, implicit cast is invalid in C++
// use
my_array[x][y];
// free memory after use
free(my_array);
在C++中,它略有不同。类似于C的方法是使用new
,遗憾的是,在C++中,它不支持可变长度数组:
double * my_array = new double[xsize*ysize];
// use
my_array[x * ysize + y];
// free
delete my_array;
这种用法有效,但在C++中不鼓励使用,建议使用vector
类,它的行为与Java的ArrayList
类似
std::vector<std::vector<double>> my_array; // auto-initialised
// use
my_array[x][y];
// no need to free, it is removed automatically by the destructor for vector
- Malloc void return char 数组有时不起作用(Terry Davis 对 C++);
- 如何通过 malloc 为队列数组分配内存?
- 如果我使用malloc()而不是堆栈数组,OpenGL不会渲染对象
- malloc()内存损坏仅通过为特定数量编写int数组
- 将指针数组传递给数组,以便在 malloc() 发生的位置发挥作用
- 2D 数组内存分配 (malloc) 返回 NULL
- 三维数组c++中的访问冲突(使用malloc)
- 如何使用malloc从一维数组转换为二维数组
- 包含字符串数组的结构的malloc问题
- 字符指针指向字符串,然后指向字符串数组。"./a.out"中的错误:malloc():内存损坏:0x0900c3b0***
- C++上有 malloc 的字符串数组
- 结构中的 malloc 1D 数组
- 如何在 ANSI C 中对字符串数组进行 malloc
- 使用 new for 2D 数组重写此 malloc
- libpng 的C++抽象导致 malloc 崩溃 -- 删除 2D 数组"Jagged"
- 带有 malloc 的 FILE 指针的二维数组
- 在汇编中使用malloc分配的内存-希望在c++中将其转换为三维数组
- 在使用malloc的数组中出现SIGSEGV错误
- 结构中数组的c++malloc
- 多维数组——malloc vs new