I have three funcitons that all have arrays. I need to make a print function. Here is one of the functions.

void findUpperCase()
{

    infile.open("trytext.txt");
    int count = 0;
    char letters[MAX_LETTERS];
    int upperLetters[26] = {0};


    while ( infile.peek() !=EOF )
    {

        infile >> letters[count];
        count++;
    }

    infile.close();

    for ( int i = 0 ; i < count ; i++ )
    {
            if ( letters[i] >= 'A' && letters[i] <= 'Z' ) 
        {
            upperLetters[letters[i]-'A']++;
        }
    }

   for ( int i = 0 ; i < 26 ; i++ )
   {
         cout << (char)(i +'A') << " occurs " <<  upperLetters[i] << " times entered" << endl;
   }

}

I think I need to return the upperLetters array so I can call it in a print function, but I have no idea if you can return an array, or how I would do that.
I want to use this in the print function

for ( int i = 0 ; i < 26 ; i++ )
       {
             cout << (char)(i +'A') << " occurs " <<  upperLetters[i] << " times entered" << endl;
       }

Inside any function, anything you create on the stack (which is effectively anything you don't make with new or malloc) ceases to exist when the function ends. So the array you make like this int upperLetters[26] = {0}; ceases to exist when the function ends. If you try to return it, you'll be returning a pointer to the start of it which is a pointer to memory that somethign else will happily write over.

Here are three options:

1) Create it using new, and then remember to delete it later. This is a pain.
2) Create it outside the function (i.e. in the caller) and pass in a pointer to it that the funciton can use to play with the array.
3) Use a proper C++ vector object and return it.

This is a case where you should pass a reference to the array you want to store the data in from the caller. Example:

void printUpperLetters()
{
    char upperLetters[26];

    ::memset(upperLetters,0,26);
    findUpperCase(upperLetters);
    for ( int i = 0 ; i < 26 ; i++ )
    {
         cout << (char)(i +'A') << " occurs "
              <<  upperLetters[i] << " times entered" << endl;
    }
}
void findUpperCase(char[]& upperLetters)
{
    infile.open("trytext.txt");
    char letters[MAX_LETTERS];
    int count = 0;
    while ( infile.peek() !=EOF )
    {
        infile >> letters[count];
        count++;
    }
    infile.close();
    for ( int i = 0 ; i < count ; i++ )
    {
        if ( letters[i] >= 'A' && letters[i] <= 'Z' ) 
        {
            upperLetters[letters[i]-'A']++;
        }
    }
}
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.