Monday, October 19, 2009

Pointers- Example 3

/*Program to reverse the string using pointers.
name contains the string to be reversed.
revname will contain the reversed string.
first allocate memory for revname which will be
equal to the string-length of name plus the null-character.
Then start scanning the last byte of name and put it in the first
byte of revname(pointed to by the variable dummy). Continue this until
the number of bytes transferred equals the string-length of name. Finally
insert the null character in revname and terminate the string.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
char *name = "Leprechaun";
int length = strlen(name);
char *revname = malloc(length+1);
char *dummy = revname;
length = length -1; //index to the last byte of name.
for(;length>=0;length--){
*dummy = *(name+length); //or name[length]
dummy++;
}
*dummy = '\0'; //Put the null character in the reversed string.
printf("The reverse of %s is %s\n", name,revname);
free(revname);
return 0;
}

No comments:

Post a Comment