如何在C ++中初始化指向动态2D数组的指针

基顿·鲁(Keaton Roux)

我给的是一个冒险家类,其中包含许多函数和成员变量。其中之一是:

string*** items;

所以首先我以为这是我必须制作的3d数组,但有人告诉我它应该是指向2d数组的指针。

我试图做的是制作一个临时数组

string** temp;

初始化并填充它,然后将项目指向temp

items = &temp;

直到功能退出为止。然后我们尝试在项目内部调用索引值

cout<<*item[0][0];

空无一物。当温度消失时,数组也消失。

这条线也工作

(*items) = new string*[2];

我在网上找不到任何对我有帮助的东西。

如何初始化项目或保留使用temp制作的数组数据。

对于那些要求提供代码的人,这是他们给我的:

class Adventurer{
private:
    string*** items;
    string name;
    double maxCarryWeight;
    double currentCarryWeight;
    int currentNumberOfItems;
    int maxNumberOfItems;
    double health;
    static int numberOfAdventurers;


public:
    Adventurer(); //default constructor
    Adventurer(const Adventurer& a);  //copy constructor
    ~Adventurer();
    bool pickUpItem(string it, double weight);
    bool dropItem(string it);
    bool dropItem(int index);
    void setName(string n);
    string getName() const;
    void setMaxCarryWeight(double w);
    double getMaxCarryWeight() const;
    void setCurrentCarryWeight(double w);
    double getCurrentCarryWeight() const;    
    void setMaxNumberOfItems(int n);
    int getMaxNumberOfItems() const;
    void setCurrentNumberOfItems(int n);
    int getCurrentNumberOfItems() const;
    int getNumberOfAdventurers() const;
    void setHealth(double h);
    double getHealth() const;
    string** getItem(int index) const;
    Adventurer& operator = (const Adventurer& a);
};

并说

string*** items;

是指向二维数组的指针

斯罗林森

尚不清楚您要从问题中实现什么,但是似乎您的主要问题可能与尝试分配2D C样式std::string数组时返回局部变量的地址有关下面是一个非常基本的示例,说明如何通过返回分配的2D数组然后获取此返回值的地址并将其存储在std::string*** items变量中来避免此类问题

// allocate memory for a 2D C-style array of std::string's
std::string** allocate_2d_array(std::size_t rows, std::size_t cols) {
    std::string** items_arr = new std::string*[rows];
    for (std::size_t i = 0; i < rows; ++i)
        items_arr[i] = new std::string[cols];
    return items_arr;
}
// print each element of the 2D C-style array via a pointer to the array
void print_items(std::ostream& os, std::string*** items, std::size_t rows, std::size_t cols) {
    for (std::size_t i = 0; i < rows; ++i) {
        for (std::size_t j = 0; j < cols; ++j)
            os << (*items)[i][j] << ' ';
        os << '\n';
    }
}
// destruct the 2D C-style array
void deallocate_2d_array(std::string** items_arr, std::size_t rows, std::size_t cols) {
    for (std::size_t i = 0; i < rows; ++i)
        delete[] items_arr[i];
    delete[] items_arr;
}
int main(void) {
    std::size_t rows = 3;  // matrix rows
    std::size_t cols = 3;  // matrix columns
    // allocate a 2D array of std::string's
    std::string** items_arr = allocate_2d_array(items, 3, 3);
    // set the pointer to a 2D std::string array to address of items_arr
    std::string*** items = &items_arr;
    int count = 0;
    // fill items_arr with data via items pointer
    for (std::size_t i = 0; i < rows; ++i) {
        for (std::size_t j = 0; j < cols; ++j) 
            (*items)[i][j] = std::to_string(++count);
    }
    print_items(std::cout, items); // print matrix to terminal
    deallocate_2d_array(items_arr, rows, cols);  // deallocate items_arr
}

但是,正如评论中提到的那样,这与现代c ++并不一致,因此人们更愿意使用astd::vector<std::vector<std::string>>存储std::string实例矩阵

您提到使用std::vector不是一种选择,但是我怀疑您的老师可能没有说出任何关于使用类似于语义的自己的准系统动态数组的std::vector想法,因此这始终是解决这些愚蠢限制的一种方法。考虑到这一点,下面是一个非常基本(未经测试)的类的框架,该类模仿了std::vector(无需使用分配器)这将使您的任务更加简单。

template<typename Ty>
class dynamic_array {
public:
    typedef Ty value_type;
    typedef Ty& reference;
    typedef const Ty& const_reference;
    typedef Ty* pointer;
    typedef const Ty* const_pointer;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;
    // CONSTRUCTION/ASSIGNMENT
    dynamic_array()
        : arr_capacity(0), arr_size(0) {}
    dynamic_array(size_type count)
        : arr_capacity(count), arr_size(count) { allocate(count); }
    ~dynamic_array() { destroy(); }
    dynamic_array& operator=(dynamic_array _other) {
        swap(*this, _other);
        return *this;
    }
    // CAPACITY
    bool empty() const noexcept { return arr_size; }
    size_type size() const noexcept { return arr_size; }
    size_type capacity() const noexcept { return arr_capacity; }
    void reserve(size_type new_cap) { if (new_cap > arr_capacity) reallocate(new_cap); }
    // ELEMENT ACCESS
    reference operator[](size_type n) { return arr[n]; }
    const_reference operator[](size_type n) const { return arr[n]; }
    // MODIFIERS
    void clear() {
        for (size_type i = 0; i < arr_size; ++i)
            (&arr[i])->~value_type();
        arr_size = 0;
    }
    void push_back(const value_type& _val) {
        if (arr_size == arr_capacity) // TODO: expand arr using reallocate
        pointer val = new (arr + arr_size) value_type(_val);
        ++arr_size;
    }
    void pop_back() {
        (&arr[arr_size-1])->~value_type();
        --arr_size;
    }
    void swap(dynamic_array& _other) {
        std::swap(arr, _other.arr);
        std::swap(arr_capacity, _other.arr_capacity);
        std::swap(arr_size, _other.arr_size);
    }
    static void swap(dynamic_array& lhs, dynamic_array& rhs) { lhs.swap(rhs); }
private:
    value_type* arr;
    size_type arr_capacity;
    size_type arr_size;
    void allocate(size_type n) { arr = new value_type[n]; }
    void reallocate(size_type new_cap) {
        value_type* tmp = new value_type[new_cap];
        size_type tmp_rows = (new_cap > arr_capacity) ? arr_capacity : new_cap;
        for (size_type i = 0; i < tmp_rows; ++i)
            tmp[i] = std::move(arr[i]);
        delete[] arr;
        arr = tmp;
        arr_capacity = new_cap;
    }
    void destroy { clear(); delete[] arr; }
};

然后,您不必花很多时间处理原始指针和它们带来的麻烦,而只需遍历dynamic_array<dynamic_array<std::string>>类实例,而不必担心内存管理。


注意:上面的dynamic_array类未经测试,可能需要进行一些调整,它也不是实现STL样式的容器的绝佳示例(您需要分配器和迭代器支持),它仅是作为std::vector模仿容器的准系统而设计的“无向量”任务要求。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章