-6

We called the function foo(&x, &y) in the main function but then why did we call swap (x, y) inside void foo function as swap (&x, &y)?

#include <stdio.h>
#include <stdlib.h>

void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
void foo(int*p1, int*p2) {
    *p1 += *p2;
    swap(p1, p2);
    *p2 *= *p1;
}

int main(){
    int x = 5, y = 9;
    foo(&x, &y);

    printf("x=%d\n", x);
    printf("y=%d\n", y);

    system("PAUSE");
    return 0;
}
Gerhardh
  • 11,688
  • 4
  • 17
  • 39
Krasnyy
  • 1
  • 4

1 Answers1

2

The difference is the type of the parameters you call the function with.

First case:

The type of x is int and the foo function is expecting int *.

So you have foo(&x, &y);

Second case:

The type of p1 is int * and the swap function is also expecting int *.

So you have swap(p1, p2);

senerh
  • 1,315
  • 10
  • 20