Hey guys,
I am still pretty new to C++ and am completely self-taught up to this point. I am currently learning about try, throw, and catch statements for exceptions and am trying to incorporate this into my programs. I know that normally when you allocate new dynamic memory, if the allocation fails you will receive a bad_alloc exception. Below is the portion of my code where this allocation takes place:
struct applicant{
char degree;
int age;
int exp;
bool interview;
int finalScore;
};
int num;
cout << "Please enter the number of applicants (1 - 10):";
cin >> num;
try
{
applicant *applicants = new applicant[num];
}
catch(bad_alloc&)
{
cout << "Error: Dynamic Memory Allocation Failed. Program Terminating."
<< endl;
cin.get();
return 0;
}
If the program encounters an exception on the memory allocation, I want the program to display the above line and then exit. Please note that in forming this code, I looked at the following website for proper syntax: http://cplusplus.com/doc/tutorial/exceptions/ (towards the bottom it explains exceptions for dynamic memory allocation)
Now, before I put this allocation into a try block and added the catch block, the program compiled and ran as expected (I am using Visual C++ 2008 Express with windows XP SP3). Now the program will not compile at all. All of the errors that I am receiving point to any place that I make any reference to a member of my applicant struct (i.e. displaying something, getting user input, etc...). Below are some of the errors I am receiving:
1>c:\documents and settings\drake reporto\my documents\visual studio 2008\projects\dynamicinterview\dynamicinterview\sourcecode.cpp(41) : error C2065: 'applicants' : undeclared identifier
1>c:\documents and settings\drake reporto\my documents\visual studio 2008\projects\dynamicinterview\dynamicinterview\sourcecode.cpp(41) : error C2228: left of '.degree' must have class/struct/union
1>c:\documents and settings\drake reporto\my documents\visual studio 2008\projects\dynamicinterview\dynamicinterview\sourcecode.cpp(43) : error C2065: 'applicants' : undeclared identifier
1>c:\documents and settings\drake reporto\my documents\visual studio 2008\projects\dynamicinterview\dynamicinterview\sourcecode.cpp(43) : error C2228: left of '.age' must have class/struct/union
Here are lines 41 - 44 for your reference:
cout << "Age: ";
cin >> applicants[i].age;
cout << "Years Experience: ";
cin >> applicants[i].exp;
Can anybody help point me in the correct direction of how to fix this?
-D