c program - swap using pointers
The following code will produce segmentation fault error due to the uninitialized pointer.
int swap(int* x, int* y)
{
int *t;
*t = *x;
*x = *y;
*y = *t;
return 0;
}
{
int *t;
*t = *x;
*x = *y;
*y = *t;
return 0;
}
corrected code is as follows,
int swap(int* x, int* y)
{
int t;
t = *x;
*x = *y;
*y = t;
return 0;
}
{
int t;
t = *x;
*x = *y;
*y = t;
return 0;
}
completed working code,
#include<stdio.h>
int swap(int*,int*);
int main()
{
int a, b;
printf("Enter value for a and b: ");
scanf("%d %d", &a, &b);
printf("\nValues before swap a=%d and b = %d", a, b);
swap(&a, &b);
printf("\nValues after swap a=%d and b = %d", a, b);
}
int swap(int* x, int* y)
{
int t;
{
int t;
t = *x;
*x = *y;
*y = t;
return 0;
}
*x = *y;
*y = t;
return 0;
}
Comments
Post a Comment