Exercise pointer and function in C
I am writing a program for "swap" using pointers that accepts the values of two variables and write a function in which we take two integers and then display them by swapping the values. Here's the solution, but I can not compile
Code:
/*Swap*/
#include<stdio.h>;
#include<conio.h>;
void swap (int *x,int *y){
int val;
val=*x;
*x=*y;
*y=val;
}
void main(){
int a;int b;
clrscr();
scanf("%d%d,&a,&b);
swap(a,b);
printf("a=%d,b=%d",a,b);
do{}
while(kbhit()==0);
}
Re: Exercise pointer and function in C
swap( &a, &b );
you pass an address not a value.
After conio, clrscr and scanf gives envy to vomit
Re: Exercise pointer and function in C
Quote:
Originally Posted by
fellah
swap( &a, &b );
you pass an address not a value.
After conio, clrscr and scanf gives envy to vomit
It is a start.
You could also notice the prototype hand, after the #include
Code:
/*swap*/
#include<stdio.h>
#include<conio.h>
void swap(int *x,int *y)
{
int val;
val=*x;
*x=*y;
*y=val;
}
int main(void)
{
int a;
int b;
clrscr();
scanf("%d%d,&a,&b);
swap(&a,&b);
printf("a=%d,b=%d",a,b);
do{}
while(kbhit()==0);
return 0;
}
Re: Exercise pointer and function in C
This is sufficient:
Code:
/*swap*/
#include <stdio.h>
void swap (int *x, int *y)
{
int val = *x;
*x = *y;
*y = val;
}
int main (void)
{
int a;
int b;
if (scanf ("%d%d", &a, &b) == 2)
{
printf ("a = %d, b = %d\n", a, b);
swap (&a, &b);
printf ("a = %d, b = %d\n", a, b);
}
return 0;
}