By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,605 Members | 1,488 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,605 IT Pros & Developers. It's quick & easy.

please answer me,,

P: 11
hi evryone..
i've couple quistions for you.. and i hope you answer it,,

1\ my dear computer dosen't run the c++ source file..even there is no error..
and that file is the only one i open..if there is any one know..please help me..

2\ i have an array of objects and i want the user to enter the size of the array ..
how am i going to do that..???
thats all...thank you
Nov 9 '06 #1
Share this Question
Share on Google+
1 Reply


Ganon11
Expert 2.5K+
P: 3,652
I can help you with number 2:

In order to allow the user to input the size of the array, you have 2 options:

1) Create a very large array, such as int array[1000]. Ask the user for input into a variable size, and then perform operations only on array[0]...array[size-1]; For example:

Expand|Select|Wrap|Line Numbers
  1.  int array[1000]; 
  2. int size;
  3. cout << "How many values? ";
  4. cin >> size;
  5. for (int i = 0; i < size; i++) {
  6.    cout << "Enter value " << i + 1 << ": ";
  7.    cin >> array[i];
  8. }
However, there is a lot of wasted computer space, since a user may enter a small value (such as 10) for size and leave 990 integer values unused.

Therefore, the much better solution is

2) Use pointers. A pointer is a special type of variable most useful for this type of array and large data structures. It would be impossible for me to fully explain pointers to you, so I will limit my description to pointer arrays.

You know that you cannot execute the following statements:

Expand|Select|Wrap|Line Numbers
  1.  int size; 
  2. cout << "Please enter the size: ";
  3. cin >> size;
  4. int array[size];  // Error!  C++ requires a constant
However, by making array a pointer, you can do this. To make array a pointer, use this statement:

Expand|Select|Wrap|Line Numbers
  1.  int *array; // NOT int array[whatev];
Then you can prompt the user for input into size, and finally say

Expand|Select|Wrap|Line Numbers
  1.  array = new int[size];
For general purposes, these are the only changes you need to know about for pointers. You can now treat array the same as a regular integer array.

Your resulting code would be:

Expand|Select|Wrap|Line Numbers
  1.  int size; 
  2. int *theArray;
  3. cout << "Please input the size: ";
  4. cin >> size;
  5. theArray = new int[size];
  6.  
  7. for (int i = 0; i < size; i++) {
  8.    cout << "Please enter value " << i + 1 << ": ";
  9.    cin >> theArray[i];
  10. }
Nov 9 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.