Here is the corrected version of your program, which will execute correctly.
There are a number of things going wrong in the sample you posted:
Incorrect Argument type being passed:
swap(a,b);
should be :
swap(&a,&b);
Your function expects pointer to the integers to be modified, You are not doing so.
Incorrect Format specifiers for printf
:
printf("%d\n%d\n",x,y);
should be:
printf("%d\n%d\n",*x,*y);
printf
is not type safe and you need to ensure you use proper format specifiers while using it. Using incorrect format specifiers results in Undefined Behavior.
The next two are good practices if not errors and you should follow them.
Incorrect return type of main()
:
As per the Standard a program should return int
,
void main()
should be
int main()
Also, add return a value return 0;
at the end of main
.
Function Declaration:
You should declare the function swap()
correctly before main
:
void swap(int *x,int *y);
Providing a function declaration before the place where you use it in code, gives the compiler a opportunity to match the parameters and report incorrect types being passed.
Further using malloc
as you have would not acheive what you are trying to achieve, You do not need to use malloc
here at all and One should always avoid using it as much as possible.
Also, You should pick up a good book and learn the basics.