How do I "resize" an array?

This is a discussion on How do I "resize" an array? within the C++ Programming forums, part of the General Programming Boards category; Maybe this is stupid, but this is the code: Code: #include<iostream.h> #include<stdio.h> //#include"..\libs\myutil.h" int main(){ int ofnum; //<---declaration cout << ...

  1. #1
    A Banana Yoshi's Avatar
    Join Date
    Oct 2001
    Posts
    859

    How do I "resize" an array?

    Maybe this is stupid, but this is the code:

    Code:
    #include<iostream.h>
    #include<stdio.h>
    //#include"..\libs\myutil.h"
    int main(){
       int ofnum;             //<---declaration
       cout << "How many number to enter: ";
       cin >> ofnum;
       double numbers[ofnum]; //<----------------------------problem
    	for(int x=0;x <=ofnum-1; x++){
       	cout << "Enter number #" << (x+1) << ": "; // <---ask for number 5 times
          cin >> numbers[x];
       }
       double total = numbers[0];
       for(int x=1;x<=ofnum-1;x++){   // <---- add all together
       	total +=numbers[x];
       }
       total/=ofnum;           //<---get average
       cout << "Average is: " << total << endl; // <----display result
       getchar();
       return 0;
    }
    it says it can only accept constants. My teacher won't help me.
    Yoshi

  2. #2
    Registered User Dr. Bebop's Avatar
    Join Date
    Sep 2002
    Posts
    96
    Use new on a pointer instead of an array.
    Code:
    #include<iostream.h>
    #include<stdio.h>
    
    int main(){
            int ofnum;
            cout << "How many number to enter: ";
            cin >> ofnum;
            double *numbers = new double[ofnum];
            for(int x=0;x <=ofnum-1; x++){
                    cout << "Enter number #" << (x+1) << ": ";
                    cin >> numbers[x];
            }
            double total = numbers[0];
            for(int x=1;x<=ofnum-1;x++){
                    total +=numbers[x];
            }
            total/=ofnum;
            cout << "Average is: " << total << endl;
            delete [] numbers;
            getchar();
            return 0;
    }
    Processing error: Stupidity detected.
    ------------------------------
    Dr. Bebop
    Windows XP Professional Ed.
    Microsoft Visual Studio 6

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 08:25 PM
  2. from 2D array to 1D array
    By cfdprogrammer in forum C Programming
    Replies: 17
    Last Post: 03-24-2009, 11:33 AM
  3. Replies: 6
    Last Post: 11-09-2006, 03:28 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 10:54 AM
  5. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 08:48 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21