pulling an array from a function

The function i've made creates an array. How do i access this array in the main area?
Thank you Duoas, now is it possible to pass an array to the function, edit it, and access it later?
Last edited on
If it is a local variable, you can't; it is destroyed when your function returns:
1
2
3
4
5
6
7
8
9
10
11
12
void foo()
{
  int a[ 10 ];
  for (int i = 0; i < sizeof( a ) / sizeof( int ); i++)
    a[ i ] = i;
}

int main()
{
  foo();
  // a[] doesn't exist here
}


If it is a global variable, just use its name:
1
2
3
4
5
6
7
8
9
10
11
12
13
int a[ 10 ];

void foo()
{
  for (int i = 0; i < sizeof( a ) / sizeof( int ); i++)
    a[ i ] = i;
}

int main()
{
  foo();
  std::cout << a[ 7 ] << std::endl;
}


If it is a heap variable, then you need to pass the address back to the main function:
1
2
3
4
5
6
7
8
9
10
11
12
13
int *foo()
{
  int *result = new int[ 10 ];
  for (int i = 0; i < 10; i++)
    result[ i ] = i;
  return result;
}

int main()
{
  int *a = foo();
  std::cout << a[ 7 ] << std::endl;
}


Hope this helps.
Topic archived. No new replies allowed.