Swap two strings using pointers
C program to swap two strings using pointers.
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 50
void swap(char *str1, char *str2)
{
char *temp = (char *)malloc((strlen(str1) + 1) * sizeof(char));
strcpy(temp,str1);
strcpy(str1,str2);
strcpy(str2,temp);
}
void main()
{
char str1[MAX], str2[MAX], temp[MAX];
printf("Enter first string\t:");
gets(str1);
printf("Enter second string\t:");
gets(str2);
printf("\nBefore swapping");
printf("\nFirst string\t:%s",str1);
printf("\nSecond string\t:%s",str2);
swap(str1, str2);
printf("\n\nAfter swapping");
printf("\nFirst string\t:%s",str1);
printf("\nSecond string\t:%s",str2);
getch();
}
Output
Enter first string :welcome
Enter second string :coursecrux
Before swapping
First string :welcome
Second string :coursecrux
After swapping
First string :coursecrux
Second string :welcome