please answer me,,

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dreams
    New Member
    • Nov 2006
    • 11

    #1

    please answer me,,

    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
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    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:

    Code:
     int array[1000]; 
    int size;
    cout << "How many values? ";
    cin >> size;
    for (int i = 0; i < size; i++) {
       cout << "Enter value " << i + 1 << ": ";
       cin >> array[i];
    }
    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:

    Code:
     int size; 
    cout << "Please enter the size: ";
    cin >> size;
    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:

    Code:
     int *array; // NOT int array[whatev];
    Then you can prompt the user for input into size, and finally say

    Code:
     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:

    Code:
     int size; 
    int *theArray;
    cout << "Please input the size: ";
    cin >> size;
    theArray = new int[size];
     
    for (int i = 0; i < size; i++) {
       cout << "Please enter value " << i + 1 << ": ";
       cin >> theArray[i];
    }

    Comment

    Working...