Home > Programming > Functions using the "C" programming language > example19.c

 

Previous

Next


/*
    In this example we demonstrate a function that takes two string parameters
    and exchange them
*/
#include <alloc.h>
#include <stdio.h>
#include <string.h>
#include <conio.h>

#define MAX(a,b) a>b?a:b

/*
    Function prototype, take as parameters pointer to char
*/
void str_swap(char *, char *);

void main()
{
    char *s1 = "First string\0";
    char *s2 = "Second string\0";
    printf("Before swaping : s1 = %s, s2 = %s.\n\n", s1, s2);
    str_swap( s1, s2 );
    printf("After swaping : s1 = %s, s2 = %s.\n\n", s1, s2);
    getch();
}

void str_swap(char *s1, char *s2)
{
/* Allocate memory for temporary string. */
    char *s = (char *)malloc(MAX(strlen(s1) ,strlen(s2)));
    strcpy(s, s1);
    strcpy(s1, s2);
    strcpy(s2, s);
/* Free up memory */
    free(s);
}


© 2004 Jim Valavanis

Previous

Next

1