Computer Science Canada

scope and freestore

Author:  Geminias [ Sun Nov 13, 2005 9:01 pm ]
Post subject:  scope and freestore

if i make a function and i create a variable on the freestore and a pointer to point to its location, how do i get access to that variables value once the function returns. i'm guess i have to make the pointer public somehow? or how would i do this besides put it into a class and declare it public?

Author:  wtd [ Mon Nov 14, 2005 12:18 am ]
Post subject: 

Have the function return the pointer.

c++:
int *foo()
{
   return new int(42);
}

int main()
{
   int *bar = foo();
}

Author:  Geminias [ Mon Nov 14, 2005 3:06 pm ]
Post subject: 

good, the only thing is i'd hate to have to make a function for each pointer i'd like to return, what's the format for returning multiple items? or can you return multiple items? lol

eg. return 0; //0 is one item.
return 0 << 3 << 5; // if the sytanx were correct it would return 3 items.

Author:  wtd [ Mon Nov 14, 2005 5:42 pm ]
Post subject: 

If you dynamically allocate an array, you can return it as a pointer.

c++:
int *foo()
{
   int *output = new int[2];
   output[0] = 4;
   output[1] = 5;
   return output;
}

int main()
{
   int *bar = foo();
}


Or you could use a std::vector, or a std::pair object.

Other languages make it much easier to return multiple values.

Author:  Geminias [ Wed Nov 16, 2005 10:54 pm ]
Post subject: 

great, thanks.


: