function return dynamic array data

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • macus
    New Member
    • Jul 2007
    • 5

    function return dynamic array data

    Dear All,

    I would like to write a small function which will return a dynamic array.
    The function is a simple function like this:
    Code:
    function_a(int a, int b)
    {
    }
    but, it will return a dynamic array values like this:
    peter 5 60.00
    mary 6 70.20
    ...

    How I do this in c++!? use function pointer ?? or other method !?
    Moreover, how can I get the return values from the main() function!?
    Since I am a newbie in C++, please provide some sample code. thanks a lot.
    Last edited by sicarie; Jul 23 '07, 01:04 PM. Reason: Code tags
  • sicarie
    Recognized Expert Specialist
    • Nov 2006
    • 4677

    #2
    I believe we need more information to help you. How were the values of the array created? How will the function have access to them? Is it supposed to create them? Are there a set number of elements in the array?

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      You cannot return an array.

      You can only return a type or a pointer and an array is not a type. Rather, it is a container of some type.

      However, in C++, the name of an array is the address of element 0 which makes the name of an array a pointer. - and you can return a pointer.

      So if you allocate an array of int:

      int* array = new int[100];

      then you can return the name "array". Your function would have an int* return value.

      This only works with one-dimensional arrays.

      With a 2D array, the name of the array is the address of element 0 which is now also an array. You cannot return the address of an array. Again, that's because it's not the address of a type.

      In this case, you use a pointer-to-pointer argument in the function.
      [code=cpp]
      void func(int (**arg)[3] )
      {
      *arg = new int[3][3];
      }
      [/code]

      You call the function with:

      [code=cpp]
      int (*ptr)[3]; //pointer to an array of 3 int

      func(&ptr); //call function with address of pointer.
      //the function will put the address of the array
      //in the pointer
      [/code]

      Comment

      Working...