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

时间:2016-08-21 13:55:06

标签: c++ arrays pointers dynamic 2d

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

string*** items;

所以首先我认为这是一个我必须制作的3d数组,但我被告知它是一个指向二维数组的指针。

我尝试做的是制作临时数组

string** temp;

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

items = &temp;

直到函数退出为止。然后我们尝试在项目

中调用索引值
cout<<*item[0][0];
什么也没有。当temp消失时,数组也会消失。

此行也是最重要的工作

(*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数组的指针

1 个答案:

答案 0 :(得分:0)

目前还不完全清楚你要从你的问题中实现什么,但似乎你的主要问题可能是在尝试分配你的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 ++不一致,而更倾向于使用std::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模仿容器来解决“无向量”任务要求。