View Single Post
Join Date: Apr 2004
Posts: 4,461
Reputation: Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future 
Solved Threads: 254
Team Colleague
Dave Sinkula's Avatar
Dave Sinkula Dave Sinkula is offline Offline
long time no c

Re: Return Array from C++

 
0
  #2
May 11th, 2004
Originally Posted by tlee
However, my current knowledge does not allow me to see how the pointer can solve this C++ limitation (return a pointer might be dangerous because it might point to the address of local variable, and this variable will go out of scope. Hence, this pointer will point to invalid value). I appreciate for your information.
Pass a pointer to the start as a parameter to the function, and then return this pointer when you're done.
  1. #include <iostream>
  2.  
  3. int *foo(int *array)
  4. {
  5. int *start = array;
  6. while ( *array )
  7. {
  8. std::cout << *array++ << ' ';
  9. }
  10. std::cout << std::endl;
  11. return start;
  12. }
  13.  
  14. int *bar(int *array)
  15. {
  16. int *start = array;
  17. while ( *array )
  18. {
  19. *array++ += 1;
  20. }
  21. return start;
  22. }
  23.  
  24. int main()
  25. {
  26. int myarray[] = {1,2,3,4,5,0};
  27. foo(bar(foo(bar(foo(myarray)))));
  28. return 0;
  29. }
  30.  
  31. /* my output
  32. 1 2 3 4 5
  33. 2 3 4 5 6
  34. 3 4 5 6 7
  35. */
Reply With Quote