-
C++ Help!
hello, im a c++ newbie and i want to write this code,
it looks as it should work but errors appear because
im declaring arrays with variables instead of real numbers
check it out:
#include<iostream.h>
void main()
{
int x;
cout<<"Enter a number for x:";
cin>>x;
int ary[x]; // the error is here
}
is there anyway i could make this work?
-
Hi Osiris, you can't declare an array with no specific value in it unless it is a pointer. Try this:
#include<iostream.h>
void main()
{
int x;
cout<<"Enter a number for x:";
cin>>x;
int *ary[x]; // the error is here
}
-
thanx, but i have some more question, can be assigned numbers just as any variable would, or they have to point to a certain variable, and would it work the same for char's?
editted:
it still gives me an error :confused:
-
linoleums solution will only get you in trouble and doesn't work anyway because it doesn't remove the source of the problems.
You can't use a variable as the size specifier for an array. The solution is to allocate memory dynamically using the new operator. WARNING: dynamic memory allcation is a semi-advanced topic. If you are a real newbie you should do other things now.
Usage of new:
Code:
int main()
{
int* ar = NULL; // this will later point to the allocated memory
int x;
cin >> x;
arr = new int[x];
// Now you can use it.
// The next line is extremely important!
delete[] arr; // do this when you're finished
return 0;
}
You should not use dynamic memory until you know pointers well.
-
#include<vector> is really easy to use