Friday, June 20, 2014

Strings Swapping using pointers , malloc() & strcpy()

We know that to swap two numbers in c programming language is much easy but can we swap two strings? Of course you can perform swapping on strings as well. The following program swap two strings using pointers, malloc() and strcpy().

#include<stdio.h>
#include<string.h>
#include<malloc.h>
void header()
{
    printf("\n\n\n\n\n\n\n\t\tBUILT AND DESIGNED BY >> ARSLAN UD DIN SHAFIQ\n\n\t\tWebsite>>\twww.CWorldbyAS.blogspot.com\n");
    printf("\n\t\tCOMSATS Institute of Information Technology,\n\n\t\t\t\t\t  Lahore , Pakistan\n\n\n");
}
int main()
{
    char s1[100],s2[100];
    char *hold;
    header();
    system("pause");
    system("cls");
while (!feof(stdin))
{
    printf("Enter String 1 : ");
    gets(s1);
    printf("\nEnter String 2 : ");
    gets(s2);
    hold=malloc(0); //is used to provide memory for pointer *hold
    strcpy(hold,s1);
    strcpy(s1,s2);
    strcpy(s2,hold);
    printf("\n\n After Swapping \n\n ");
    printf(" String 1 : %s  ; String 2 : %s \n\n\n\n",s1,s2);
}
}

No comments:

Post a Comment