How do I decalre variables as they are needed? For instance, a user says he wants to store x numbers, how would i go about doing that?
How do I decalre variables as they are needed? For instance, a user says he wants to store x numbers, how would i go about doing that?
One way is to use dynamic memory allocation. For example:
You can declare and allocate the array in one step like this, but I prefer the above method:Code:int x; cout << "How many number do you want to store? "; cin >> x; int *numbers; numbers = new int[x]; for (i=0; i<x; i++) numbers[i] = i; for (i=0; i<x; i++) printf("numbers[%d]:%d\n",i,numbers[i]); delete []numbers;
int *numbers = new int[x];
Make sure to free the memory once you're done using it with the delete statement.
you could also use malloc / free... with these you can use user-defined type casting, i'm not sure if you can do this with new / delete...
hasafraggin shizigishin oppashigger...
Not sure?
New / delete are much better in this area than malloc, because you don't even have to case.
simply use:
class MyClass {
...
}
int x = GetCount();
MyClass* list = new MyClass[x];
// do what is needed...
delete [] list;
i see... so the [type] field doesn't necessarily need to be a C/++ keyword for a type... niice... hmm... but what are other differences? i tend to stray away from using operators and syntax that is different from what i've normally used... thanks...
hasafraggin shizigishin oppashigger...
This bit of C is very interesting.. someone mind explaining it to me? I've always been used to the C++ shortcut.Code:int x; cout << "How many number do you want to store? "; cin >> x; int *numbers; numbers = new int[x]; for (i=0; i<x; i++) numbers[i] = i; for (i=0; i<x; i++) printf("numbers[%d]:%d\n",i,numbers[i]); delete []numbers;
this code is actually C++ - it uses cin, cout, new and delete.
The only thing "C" about it is printf.
lookup printf in your documentation.
what this lines mean is to print a string. the first parameter is the string format. every % indicates a parameter to be inserted to the string with it's type - %d stands for decimal integer.
So the first %d will be replaced with the first argument - i, and the second %d will be replaced with numbers[i]
HTH