Monday, May 24, 2010

C++ heap problem (new fuction)?

How do I create an array of Employees at run time? The size of the array is entered by the user.





I tried...


cin %26gt;%26gt; num;


Employee[] emp = new Employee[num];





but its wrong.

C++ heap problem (new fuction)?
Does it need to be an array? Why don't you use a vector?





this is what vectors are used for.
Reply:This should work fine:





Employee* pemp = new Employee[num];





Then pemp[0] to get the first element, pemp[1], etc.





Ensure you never read past pemp[num-1] as that is not your memory.
Reply:1. use a array of character pointers (string)


2. then create a buffer say buffer[255] that will accept user input


3. get the length of the string entered


4. then use malloc to allocate storage for the string


5. copy the entered string to the storage allocated in 4


6. do steps 4 to 5 for every new employee
Reply:You need to initialize your Employee (class) to zero (0) before you create the array. I believe this is called the "default constructor". Also, when you the function has run its course, you must destroy the array with: delete Employee; . Otherwise, the memory (heap) manager will cause a run time error. Remember, C++ does not have automatic garbage collection, though Java does.


No comments:

Post a Comment