I'm brand new to C++ and I'm having a difficult time. I'm working on a project for school and I'm very confused with functions all together. How do I get my arrays from main so I don't have to have them in each function and how do I call each array seperately. Any insight that might get me on the right track would be appreciated.

Recommended Answers

All 5 Replies

You can't pass an actual array to a function but what you can do is pass a pointer to the first element of the array. In many ways a pointer to the first element can be used as an actual array for example

int array[5] = {5, 4, 3, 2, 1};
int* pointer = array;

cout << array[3] << ":" << pointer[3] << endl;

would output "2 : 2".

The important thing to remember is that when you pass an array to a function like this you loose all information about the size of the array so if it is important that the function knows that it has to be passed as well

void function2(int *ptr, int size);

void function1(void)
{
    int array[5] = {5, 4, 3, 2, 1};

    function2(array, sizeof array/sizeof array[0]);

    // array now contains 5, 4, 3, 2, 6
}

void function2(int *ptr, int size)
{
    // Set the last element of the passed array to value 6
    if (size > 0)
    {
        ptr[size-1] = 6;
    }
}

Sorry just saw the code, with your findMin and findMax functions you want to pass and work on a single array, like calcAvg does. The pass back the result as the return value. Don't try and print out in the functions print out in main where the functions are called.

This is generally good advice if your functions that do the calculations also do the printing then you can not reuse them in places that just require the return value. Separate the code that performs tasks from the code than prints results putting them in different functions.

Thanks alot that makes much more sense than my book. I'll start tinkering.

This is really horrible code but this is what I'm trying to accomplish I just don't know how to return all the values to main then only call each one specifically. We haven't went over pointers so I can't use them.

For what you need to do you can treat the pointer as an array, pointer[0] will work as if pointer was actually an array. Your definitions should look like this

double findMax(double array[], int size)
{
    double max;

    // Code here working on array and size to calculate max

    return max;
}

Delete the array stock1, stock2 and stock3 from the inside of findMax instead do the same operations on array to calculate the maximum value in the array which you can then return.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.