cplusplus.com cplusplus.com
cplusplus.com   C++ : Forums : Beginners : pulling an array from a function
  Search:
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forums
Forums
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programming
Articles
Lounge
Jobs

-

question  pulling an array from a function

Cbas (11)
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
Duoas (805)
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.
|

This topic is archived - New replies not allowed.
Home page | Privacy policy
© cplusplus.com, 2000-2008 - All rights reserved - v2.2
Spotted an error? contact us