c++ - 结构中的数组,指针 [C++ 初学者]

标签 c++ arrays pointers struct

我有 Java、PHP 背景,正在尝试学习 C++。我想在结构中存储一个数组。我的问题是在初始化结构后指定数组的大小。

这是我的结构代码:

struct SpriteAnimation {
    // ...
    int parts;                  // total number of animation-parts
    unsigned int textures[];    // array to store all animation-parts
    // ...
};

这里是主要功能:

SpriteAnimation bg_anim;
bg_anim.parts = 3; 
unsigned int *myarray = new unsigned int[bg_anim.parts];
bg_anim.textures = myarray;

我需要更改什么才能解决此问题?

最佳答案

在现代 C++ 中,您将为内部“数组”使用动态容器:

struct SpriteAnimation {
  std::vector<unsigned int> textures;    // array to store all animation-parts
  size_t num_parts() const { return textures.size(); }
};

到目前为止,这比您尝试使用手动分配的存储空间要安全得多,模块化程度也更高。用法:

SpriteAnimation x;
x.textures.push_back(12);  // add an element
x.textures.push_back(18);  // add another element

SpriteAnimation y = x;     // make a copy

std::cout << "We have " << x.num_textures() << " textures." std::endl; // report

关于c++ - 结构中的数组,指针 [C++ 初学者],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6969055/

相关文章:

arrays - 算法 - 以最少的交换两个连续元素的数量对数组进行排序

c++ - 引用指针问题?

c++ - C++中函数调用时的编译器错误

C++ - 从另一个类构造函数调用类构造函数

javascript - 在表格中打印网页上的数组值(json 格式)

c - 另一个大小的数组

c++ - 具有非指针/引用返回类型的协变返回类型

c++ - 如何迭代结构体中的 unordered_map ?

c++ - 使用 C++ 和 STL 实现 Dijkstra 最短路径算法

c++ - 无堆栈协程与有堆栈协程有何不同?