Hello guys. I'm a need of some assistance. I finished my C++ book yesterday (yes!) and stuck 98% of the codes into my gray matter (brain). The book ended with structures.
Example:
1 2 3 4 5 6 7 8 9 10
struct Students
{
char Name [80];
short testScore1, testScore2, testScore3;
};
// to determine the amount of students I need a constant value
constshort numStudents = 10;
Students worms [numStudents];
Now... From what I read, there was another way of getting a constant value even though the user inputted the value. This is called Dynamic Memory Allocation. Basically, a pointer is created only for one purpose and that's to hold the address/value of the users input and since it can only do that, it is known, also, as a constant value.
Example:
1 2 3 4 5 6
short num;
cout << "Enter # of students: ";
cin >> num; // this is not a constant due to the fact it can be changed
cin.ignore ();
short*stuPtr = newshort [num]; // this is a constant value and is known as stuPtr
Now, what I want to do is use the newly obtained Dynamic Memory Allocation to declare the amount of "Students" the structure will handle.
struct Students
{
char Name [80];
short testScore1, testScore2, testScore3;
};
int main (void)
{
short num;
cout << "Enter # of students: ";
cin >> num;
cin.ignore ();
short*stuPtr = newshort [num];
Students worms [*stuPtr]; // this is where the problem occurs
// ... rest of code
}
Is there something I'm doing wrong? I'm pretty sure that the newly obtained pointer is a constant value. If I'm doing it wrong then can you explain a different method of making this work? Thanks.
#include <iostream>
struct Students
{
char Name [80];
short testScore1, testScore2, testScore3;
};
int main (void)
{
short num;
std::cout << "Enter # of students: ";
std::cin >> num;
std::cin.ignore (); // why?
Students* worms = new Students[num]; // change this
// ... rest of code
delete[] worms; // add this
}
I would start out with a Principals of problem solving in C++ book to get started. (try amazon and read the reviews)
After you are familiar up to the point of pointers I would opt for an object oriented programming book to learn inheritance, polymorphism, and the STL library.
If those terms confuse don't worry, it's pretty straight forward actually. IN smaller terms those concepts are easy to learn. You won't encounter the most difficult scenarios until you start designing or working on very large programs. That's when the bugs start to rape your brain. lol