calling array


hi dear all

I wanted to know how I can use one array in one function that this array has gotten from another function . all of these functions are in one program .

Thanks alot for your help

Regards
How does that array look like? Anyway you can usually exchange the pointers to arrays.

like

1
2
3
int x[10];
DoSomething(x);
DoSomethingElse(x);


Never return the pointer to a local variable. If you want to return a pointer to an array write it like so:

1
2
3
4
5
6
7
int *Foo()
{
  int *x = new int[10];
  DoSomething(x);
  DoSomethingElse(x);
  return x;
}
Of couse you can. It's easy. Because Array's like Pointer, always use reference.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
void InputArray(int n, int A[n])
{
   for (int i=0; i<n; i++)
   {
      cout<<"A["<<i<<"]=";
      cin>>A[i];
   }
}

int SumArray(int n, int A[n])
{
   int S = 0;
   for (int i=0; i<n; i++)
      S+=A[i];
   return S;
}

int main()
{
   int n;
   cin>>n;
   int A[n];
   InputArray(n, A);
   SumArray(n, A);
   return 0;
}
micheal... that won't work on every compiler. It might be better if you take n from between the brackets...


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int SumArray(int n, int A[])
{
   int S = 0;
   for (int i=0; i<n; i++)
      S+=A[i];
   return S;
}
int main()
{
    int n;
    cin>>n;
    int A[n];
    InputArray(n,A); // fine
    return 0;
}


That should fix your code for most compilers...


If you want to go farther, you could also template the size and have two separate functions so if you have a set size (the example you have would have to call the second function with A)... I saw this somewhere and have been using it ever since... It seems to work on every compiler I've found...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void InputArray( int *A, size_t n )
{
    for (size_t i=0; i<n; i++)
    {
        cout<<"A["<<i<<"]=";
        cin>>A[i];
    }
}
template<size_t n>
void InputArray(int (&A)[n] )
{
    InputArray(A,n);
}
int main()
{
    int n;
    cin>>n;
    int A[n];
    int B[10];
    InputArray(B); // fine
    InputArray(A,n); // fine
    //InputArray(A); // error, too few arguments... it's calling the nontemplate function
    return 0;
}
oh, I wanted to add int A[n]; should probably be int *A = new int[n]; because it's dynamic... I'm not sure what people think of the using the first one...
In C++ one typically uses std::vector for this sort of thing, avoiding arrays unless you've been backed into a corner.

Topic archived. No new replies allowed.