Global arrays.

I currently have multiple functions that use globally declared arrays in my code.
I want to turn them so that arrays are no longer globally declared, but instead are passed by references to the function.

And I have a function caller inside main, and other functions are called within the function.

Is there any piece of advice to do so?

closed account (zb0S216C)
Are the length of the arrays known at compile-time? If so, then you can pass arrays like so:

1
2
3
4
5
6
7
8
9
10
11
12
int main( )
  {
    unsigned int const Array_Length_( 10u );
    int Array_[Array_Length_];

    void Print_Array( int( &Target_Array_ )[10] );
  }

void Print_Array( int( &Target_Array_ )[10] )
  {
    // ...
  }

The "Target_Array_" declaration is known as a reference to an array of n; in order for it to work, the length of the array must be known. However, if the length of the array is not known at compile-time, then the following will suffice:

1
2
3
4
5
6
7
8
9
10
11
void Print_Array( int const *Target_Array_ );

int main( )
  {
    int *Array_( ::new int[50] );
  }

void Print_Array( int const *Target_Array_ )
  {
    // ...
  }

Wazzak
Last edited on
:(
I can compile with no errors... but I cannot run the programe
- I suggest you simply define the arrays in main, and pass them as arguments to said functions.

- arrays are passed by reference to functions in C++

- Moreover, if you are calling other functions inside of functions, make sure you pass them the array if they are supposed to do operations with it.
Topic archived. No new replies allowed.