0

I have looked around, and can't find anywhere that explicitly answers how to pass an array from function1, class1 to function2, class2.

This is my code.

Game Class

void Game::userInputNumbers()
{
    for (int i = 0; i < 6; i++)
    {
    std::cin >> myNumbers[i];
    }

    for (int i = 0; i < 6; i++)
    {
        std::cout << myNumbers[i] << "   ";
    }
}

Main

game.userInputNumbers(); 
user.setTicket(int a, myNumbers[6], username);

User Class

void User::setTicket(int i, int myNumbers[6], std::string username)
{
    std::ofstream fout (username + "Ticket" + a + ".txt");

    for (int i = 0; i < 6; i++)
    {
    fout << myNumbers[i] << std::endl;
    }
}

I'm aware that I will probably have to declare the array as static (not really sure how, or what the implications of that are) and that I will have to use pointers in some form.

Also please note, username and int a have been declared elsewhere in the program and work for other functions so I'm not worried about those, and I have left out all unnecessary code such as my includes as again the rest of the program compiles fine

Thanks in advance

5
  • Function call in the main method should be this way user.setTicket(a, myNumbers, username); . Isn't it? Commented Dec 9, 2013 at 9:33
  • Either use pointer + count of elements OR (much better) use a std::vector. Commented Dec 9, 2013 at 9:34
  • yes I think you are right Commented Dec 9, 2013 at 9:35
  • can i manipulate a vector in a similar way to an array, or is it styled more like a linked list? Commented Dec 9, 2013 at 9:36
  • A vector is a dynamic array and guarantees O(1) indexing. Commented Dec 9, 2013 at 11:48

3 Answers 3

3

I suggest using std::vector instead of a normal array.

There are a couple of ways you can do this, one is something like this:

gameObject.userInputNumbers();
userObject.setTicket(value, gameObject.getMyNumbers(), username);
Sign up to request clarification or add additional context in comments.

1 Comment

this worked thanks, will research into vectors thanks for the tip
1

You can't declare a here:

user.setTicket(int a, myNumbers[6], username);

Instead, use:

user.setTicket(a, myNumbers[6], username);

Also, when passing an array, you don't need to include the array length:

user.setTicket(a, myNumbers, username);

Comments

0

Examples found here http://www.cplusplus.com/doc/tutorial/arrays/

for your case this is how you would do it:

// arrays as parameters
#include <iostream>
using namespace std;

void SetArray (int& arg[]) {
  for (int i=0; i<arg.size(); ++i)
    cin >> arg[i];
}

int main ()
{
  int myNumbers[6];
  SetArray(myNumbers);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.