Thread: Variable argument lists without using cstdarg...

  1. #1
    Registered User
    Join Date
    Jul 2012
    Posts
    36

    Variable argument lists without using cstdarg...

    Hi all,
    I am currently in the 17th tutorial in the C++ series (Variable argument list in C++)

    and i can successfully make programs with functions with unknown length of argument list....

    in that Alex Allain says that another way of doing it rather than using
    cstdarg is to make a function that accepts a pointer to an array...

    i've made a program and wanna know if that is what he meant...

    Code:
    #include<iostream>
    
    
    
    
    using namespace std;
    
    
    void avg(int size,int *a){
    
    
        int sum = 0,avg = 0,x;
        for(x = 0; x < size; x++){
    
    
            sum += *(a + x);
    
    
        }
        avg = sum / size;
        cout << "The average of the numbers is " << avg << "...";
    
    
    }
    
    
    int main(){
    
    
        cout << "How many numbers's average would you like to find? ";
        int size;
        cin >> size;
        cin.ignore();
        int array[size];
        for(int a = 0; a < size; a++){
    
    
            cout << "Enter number " << a + 1 << " here: ";
            cin >> array[a];
            cin.ignore();
    
    
        }
        int *a = array;
        avg(size,a);
        cin.get();
    
    
    }
    Last edited by tennisstar; 11-13-2012 at 12:51 AM.

  2. #2
    [](){}(); manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    *nullptr
    Posts
    2,657
    Yes.
    BTW, you need to allocate the array dynamically.
    Code:
    int* array=new int[size];
    (Also, explore containers like std::vector, std::list and std::map after you are comfortable using arrays and pointers like this. They provide comfortable interfaces for this kind of stuff)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 01-21-2009, 02:27 PM
  2. exceptions and variable argument lists
    By DavidP in forum C++ Programming
    Replies: 3
    Last Post: 10-30-2006, 05:23 PM
  3. variable argument lists
    By cProGrammer28 in forum C Programming
    Replies: 2
    Last Post: 05-03-2005, 06:27 AM
  4. variable-length argument lists
    By Naas in forum C++ Programming
    Replies: 1
    Last Post: 08-06-2002, 11:57 AM
  5. rerouting variable argument lists...
    By doubleanti in forum C++ Programming
    Replies: 9
    Last Post: 12-14-2001, 09:28 AM