2010年10月14日星期四

Return Array from C++

Re: Return Array from C++

Quote 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.
C++ Syntax (Toggle Plain Text)
  1. #include
  2. int *foo(int *array)
  3. {
  4. int *start = array;
  5. while ( *array )
  6. {
  7. std::cout << *array++ << ' ';
  8. }
  9. std::cout << class="me2">endl;
  10. return start;
  11. }
  12. int *bar(int *array)
  13. {
  14. int *start = array;
  15. while ( *array )
  16. {
  17. *array++ += 1;
  18. }
  19. return start;
  20. }
  21. int main()
  22. {
  23. int myarray[] = {1,2,3,4,5,0};
  24. foo(bar(foo(bar(foo(myarray)))));
  25. return 0;
  26. }
  27. /* my output
  28. 1 2 3 4 5
  29. 2 3 4 5 6
  30. 3 4 5 6 7
  31. */

没有评论:

发表评论