1

Possible Duplicate:
returning multiple values from a function

For example if you want a function that modifies the values of 3 pointers then you need to declare double pointers as function parameters. If you write many lines with double pointers, the code will be very hard to understand; so is there any way you can return more than one value, for example 3 input variables and 2 output ones?

int * function(int *p,int **q,int **r)
{
  ...
  return p;
}

int main(){
  int *p,*q,*r;

  ...

  p=function(p,&q,&r);

  ...

  return 0;
}
Community
  • 1
  • 1
Cristi
  • 1,195
  • 6
  • 17
  • 24
  • Do you really need to modify the pointer, or just the value that the pointer points to? – plasma Jun 17 '12 at 05:32
  • Do other similar questions answer this? e.g. http://stackoverflow.com/questions/3829167/returning-multiple-values-from-a-function – huon Jun 17 '12 at 05:33

4 Answers4

6

You can put all the variables you want to modify in a structure and return that structure from the function.
Since a structure can hold any number of elements, You can return any number of elements from a function in this way.

Ofcourse, the any as all practical values will have a limit in practical environments.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
1

You can use a struct for that or an array if the elements that you want to modify are of the same type:

struct a {
    int *p;
    int *p2;
    int *p3;
    double *p4;
    ...
} ;

int * function(struct a*);

int main()
{
     struct a a;
     function(&a);
     return 0;
}
Clifford
  • 88,407
  • 13
  • 85
  • 165
ob_dev
  • 2,808
  • 1
  • 20
  • 26
0

you can also pass pointers to the function and modify pointers in the function,but use a struct for that is better

Skyline
  • 53
  • 4
0

As has been noted, you can use a structure to aggregate multiple values. @obounaim's example demonstrates a function taking a pointer to such a structure, but it is also possible to return a structure by value which may be simpler and more readable.

typedef struct 
{
    int x ;
    int y ;
    int z ;

} coord3d ;

coord3d getPosition(void);

int main()
{
     coord3d pos = getPosition();
     return 0;
}

For large structures this may be prohibitively expensive, and if the structure contains a pointer, all copies of the structure will point to to same data, so some caution required, but often this is simpler and more intuitive. For example, if the structure contains some tightly cohesive data such as a Cartesian coordinate or a complex number, this method makes sense, and has little overhead in the return by value semantics.

Clifford
  • 88,407
  • 13
  • 85
  • 165