结构中数组的c++malloc

c++ malloc for array in struct

本文关键字:c++malloc 数组 结构      更新时间:2023-10-16

我是一名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列表的顺序进行(。

考虑将cellswidth设为私有,以避免地图用户意外直接访问它们。

在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