Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap 2 integers using pointers?

Tags:

c

when I try to swap these two integers using pointers, I get segmentation fault.

Basically before I swap, x is assigned to 1 and y is assigned to 2. After I swap x is assigned to 2 and y is assigned to 1.

The program takes two integers x and y and is supposedly meant to swap them:

int swap(int x, int y){

    int *swapXtoY;
    int *swapYtoX;

    *swapXtoY = y;
    *swapYtoX = x;
}
like image 717
Anonymous Duck Avatar asked Dec 08 '22 00:12

Anonymous Duck


1 Answers

Function swap is expecting both of its argument as int, but you are passing int *. Compiler should raise a warning about this.

It seems that you have no idea how pointers work in C. Your function is just assigning two ints to local variables. Function should be like:

int swap(int *x, int *y){

    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
like image 185
haccks Avatar answered Dec 14 '22 23:12

haccks