|
-
Mar 7th, 2002, 10:26 AM
#1
Thread Starter
Addicted Member
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?
-
Mar 7th, 2002, 10:39 AM
#2
New Member
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
}
-
Mar 7th, 2002, 10:54 AM
#3
Thread Starter
Addicted Member
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
Last edited by Osiris; Mar 7th, 2002 at 10:58 AM.
؊Ϯϊ
-
Mar 7th, 2002, 12:30 PM
#4
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.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Mar 7th, 2002, 04:21 PM
#5
Fanatic Member
#include<vector> is really easy to use
The human brain cannot hold all of the knowledge that exists in this world, but it can hold pointers to that knowledge.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|