0

My function is outside main()

it's this

void Ydisplay(int D1[])
{
 for(int i=0;i<a;i++)
  {
   cout<<"\t<<D1[i];
}

the array D1 is a dynamic array the error is 'a' is undefined it's taken from user so it has to be in main.. but is there any other option?

4

4 回答 4

1

You have to pass the array size along as a function parameter:

void Ydisplay(std::size_t len, int D1[])
{
    for (std::size_t i = 0; i != len ;++i)
    {
        std::cout << '\t' << D1[i];
    }
}

In C++, you would use a std:vector<int>, though.

void Ydisplay(std::vector<int> const & D1)
{
    for (int n : D1)
    {
        std::cout << '\t' << n;
    }
}
于 2013-07-20T10:19:52.533 回答
0

Have your function in this way.,

void Ydisplay(int D1[])
{
 cin >> a; //Remove getting input from main()
 for(int i=0;i<a;i++)
  {
   cout<<'\t'<<D1[i];
}
于 2013-07-20T10:18:47.783 回答
0

a is not know to function Ydisplay() it is local to main(), Pass value a from main.

change function syntax as:

void Ydisplay(int D1[], int a)
                         ^ add

A syntax error, missing ":

cout<<"\t" <<D1[i];
     //  ^  added
于 2013-07-20T10:20:24.323 回答
0

I think you need to understand what you are trying to do. In this particular code, You are trying to print elements that are in the array D1. So you print the element starting from D1[0] to D1[n]. You use the for loop to traverse through each element in the array D1. int i starts at i = 0 to the last element which is i < sizeof(D1)/sizeof(int). You don`t need variable a, it make no sense with what you are trying to do. To print on each line try: cout << D1[i] << endl;

于 2013-07-20T18:07:07.903 回答