1

I wanted to write a function that swaps two values, but I'm not sure how to return 2 integers. This code doesn't work, as after swapping the values x is still one and y is still 2:

void swap(int in_1, int in_2);

int main(void) 
{
    int x = 1;
    int y = 2;
    printf("x = %d\n", x);
    printf("y = %d\n", y);
    printf("swapping...\n");
    swap(x,y);
    printf("x = %d\n", x);
    printf("y = %d\n", y); 
}

void swap(int in_1, int in_2) 
{
    int temp = in_1;
    in_1 = in_2;
    in_2 = temp;
    return; 
}
  • I know that the function only swaps values inside, but how would you program this to actually swap x and y? – Jesse Aug 8 '14 at 13:16
3

This exact problem is reviewed in the lectures. In short, you have to use pointers in your swap function. I'm pretty sure it's week 4, 2nd lecture (lecture continued). Or you can check out the lecture notes here: http://d2o9nyf4hwsci4.cloudfront.net/2013/fall/lectures/4/w/notes4w/notes4w.html

    void swap(int* a, int* b)
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}
| improve this answer | |
  • Ah thanks!! Still at pset3 for now :) – Jesse Aug 8 '14 at 13:37
1

You are not required to return the two values, what your swap() function is doing is going to where the numbers are stored and subsequently changing them.

*a means go to where a is

so

temp = *a is take the value from a and store it in temp

*a = *b is take the value from b and store it where a is

this means you don't have to return anything out of your swap function.

The flipside is you need to pass pointers (int*) into the swap() function instead of just two ints.

| improve this answer | |
  • Ah thank you!!! – Jesse Aug 8 '14 at 13:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .