如何为结构数组动态分配内存...例如:
class students
{
struct stud
{
int r_no;
char name[20];
}*s;
}如何为*s动态分配内存...
发布于 2009-02-27 08:22:39
首先,这是,而不是的方式,例如,你可以使用stud的向量。使用您已有的代码,它将类似于:
class students
{
public:
struct stud ... *s;
students() // ctor
{
s = new stud[100]; // say you have 100 students
// from now on you can use s[0], s[1], etc. in the class
}
};但是,您应该使用某种STL向量或列表:
class students
{
public:
struct stud ... ;
std::vector<stud> my_students;
students() // ctor
{
stud aStudent = {0, "Student Name"};
my_students.push_back(aStudent); // add a new student.
}
};发布于 2009-02-27 08:20:01
为什么在只有一个指针的类中对结构进行额外的包装?
无论如何,在C语言中,你会这样做:
struct stud
{
int r_no;
char name[20];
} *s;
size_t num_students = 4711;
s = malloc(num_students * sizeof *s);当然,谨慎的做法是遍历并确保所有这些独立的结构都已初始化。
如果您的意思是这是C++,那么您应该编写负责这一点的构造函数,并使用new[]来分配一个结构数组。
发布于 2009-02-27 10:18:04
在可能的情况下,应该使用标准组件。在这里,std::string和std::vector会对您有所帮助。
struct Student
{
int r_no;
std::string name;
};
typedef std::vector<Student> StudentList;使用这种方法,就没有必要去考虑如何动态分配内存了。一切都安排好了!
编辑:
我只是简单地定义了StudentList,因为对我来说,给它添加更多的功能与这个问题无关。显然,最后一行可以替换为真正的类定义:
class StudentList
{
public:
// Add your own functionalities here
private:
std::vector<Student> m_students;
};https://stackoverflow.com/questions/593946
复制相似问题