I have a program that asks a user for a integer. This integer is a member of a struct statement. Later on in the program a function points to this structure in hopes of using the integer as a variable in an array. The problem that I'm seeing is that the complier, and likely the c++ coding standard, is looking for a constant to be decalared at compile. Am I thinking in the wrong way? I want to make an array that depends on the size of the input. If anyone has a moment to help me think out of the box, I would be most appreciative. Thanks all.
variable array size (constant problem)
Collapse
X
-
Define a pointer to the array. Then, later in the program when you know how big it needs to be, then you can define a constant size array, and point your pointer to it.
If the size is dynamic and will keep changing, I suggest you use a vector. It is already implemented in STL.Comment
-
Thank you for your response. The workaround that I figured was to set a constant high enough that it would be unlikely (yes I know....) that the user would ever use that variable. I then set my count variable to the size determined by user input. So I'm wasting memory, but it worked. I like your suggestion better as it seems more efficient. This program is for my final in an intro to c++ class. Thanks again!
JoshuaComment
-
Comment
-
Well, I am in the same boat. I found these forums while trying to find a way to get the size of an array from user input.
I haven't done any programming I took a class in it last year, and am trying to practice so I don't get owned in my 'programming 2' class.
What I have is something like this:
cout << "Please enter the number of salespeople/n";
int n;
cin >> n;
I want to size of the array to be 'n'. This happens at the beginning of int main().
The size of the array doesn't need to change after this. I just want it to be based on the user's input.
I didn't understand D_C's explanation at all. :/ We didn't do pointers in my first class, although we will cover them in this one. I have tried reading my book and while I sort of understand what a pointer is, I still can't apply it to my problem.
Any help or clarification will be much appreciated.Comment
-
Code:int LENGTH; int* array; cout << "Enter number of array entries: "; cin >> LENGTH; cout << endl; array = (int*)malloc(LENGTH*sizeof(int)); int i; for(i = 0; i < LENGTH; i++) { cout << "Enter an array value: "; cin >> array[i]; } for(i = 0; i < LENGTH; i++) cout << array[i] << " "; cout << endl;Comment
Comment