0

First post on StackOverflow. I'm supposed to create a function:

int sumsort(int *a, int *b, int *c)

This function should arrange the 3 values in the memory locations pointed to by a, b, and c in ascending order and also return the sum of the contents of the memory locations a, b, and c.

Here's my function:

 int sumsort(int *a, int *b, int *c) {

    int sum = *a + *b + *c;

    int sorted[] = {*a, *b, *c};

    for (int i = 0; i <= 2; i++) {

       if (sorted[0] > sorted[1]) 

       {
          int temp = sorted[1];
          sorted[1] = sorted[0];
          sorted[0] = temp;
       } // end if
       if (sorted[1] > sorted[2]) 
       {
          int temp2 = sorted[2];
          sorted[2] = sorted[1];
          sorted[1] = temp2;
       } // end if

    } // end for

    return sum;

} // end sumsort function

How can I access the sorted[] array in main? I need to print the 3 variables in ascending order but don't really see how I can do that since the sumsort function has to return the sum and the actual sorting has to happen in the sumsort function too.

I tried creating a new array variable in main and assigning it sorted[] after I call the sumsort function, but that doesn't work because it's out of scope?

2 Answers2

1

You are correct that you cannot access your sorted variable from main. But you don't need to. The point of the function is that it modifies the values pointed by its parameters.

For instance:

int main()
{
    int x = 5, y = 1, z = 3;

    int sum = sumsort(&x, &y, &y);

    // now  x == 1  ,  y == 3  , z == 5
}

This is possible. Inside sumsort you need not to create a new array, but to modify the values pointed by it's paramters.

For instance, if you had to sort just two numbers this is what you would do

void foo(int* a, int *b)
{
    if (*a > *b)
    {
        int temp = *a;
        *a = *b;
        *b = temp;
    }
}
bolov
  • 72,283
  • 15
  • 145
  • 224
0

You can declare sorted[] as global variable outside of main:

int sorted[3];
main()
{
  int a=20, b=15, c=22, sum;
 sum= sumsort(&a,&b,&c);
 printf("%d",sum);
 printf("%d", sorted[0]);
 printf("%d", sorted[1]);
 printf("%d", sorted[2]);

 }

And in your function you can use it as shown below:

 int sumsort(int *a, int *b, int *c) {

 int sum = *a + *b + *c;

 sorted[0] = *a; 
 sorted[1] = *b;
 sorted[2] = *c;
 for (int i = 0; i <= 2; i++) {

   if (sorted[0] > sorted[1]) 

   {
      int temp = sorted[1];
      sorted[1] = sorted[0];
      sorted[0] = temp;
   } // end if
   if (sorted[1] > sorted[2]) 
   {
      int temp2 = sorted[2];
      sorted[2] = sorted[1];
      sorted[1] = temp2;
   } // end if

} // end for

return sum;

} // end sumsort function

You may have to check your sorting logic.

Hope this helps :)

Gautham
  • 16
  • 1