Sunday, July 12, 2009

C++ dynamic array function help?

Write a program that will keep track of the enrollment of one class. Use a dynamic array to keep track of the enrollment. When enrolling a new student, the dynamic array will increase by one. You must use a function call to add student. I have been working on this problem all day and my code just does not work. My teacher said we do not need to use vector to increase the array size so any tips on how to solve this problem would be great because I just keep hitting a dead end.

C++ dynamic array function help?
C++ does not have any native "dynamic array" capability. The closest thing would be the use of the ANSI realloc() function, but that's a C thing, and not special to C++.


Now you *could* write your own class that manages an array. Let's say your class is something like this:





class Array {


a_class *m_array;


size_t m_nCurrentArraySize;


void Resize(size_t nNewSize);


...


};





Then your implementation might looks like this





void Array::Resize(size_t nNewSize) {


a_class *pNewArray = new a_class[nNewSize];


for (size_t i = 0; i %26lt; m_nCurrentArraySize; i++)


pNewArray[i] = m_array[i];


m_nCurrentArraySize = nNewSize;


delete [] m_array;


m_array = pNewArray;


}
Reply:You can use a linked list for this type of operation but your teacher wanted you to use 'dynamic' arrays. Nothing like making things more difficult.





one_student is assumed to be a structure.


student_class is assumed to be a dynamic array of one_student.





class MyClassArray


{


public:


MyClassArray() {student_enrol = NULL; student_count = 0;}


void AddStudent(one_student %26amp;student);


private:


typedef one_student *student_array;


student_array student_enrol;


int student_count;


...


};





MyClassArray::AddStudent(one_student %26amp;student)


{


student_class temp = new one_student[student_count+1];


for (int i = 0; i %26lt;= student_count; ++i)


temp[i] = student_enrol[i];


temp[student_count++] = student;


delete student_enrol;


student_enrol = temp;


}
Reply:It might be useful for you to paste the code you've got, and tell us specifically what error you're seeing.


No comments:

Post a Comment