Programming in C Project Organization Compiler Directives 7/28/09
A Real C Program • Program that accepts one command line argument. • Treats the command line argument as a string, and reverses the letters in the string. • Prints out the reversed string. 7/28/09
reverse. c - part 1 /** reverse. c ** inputs a single command line argument which is a string ** to be printed with its characters reversed. ’ ** Use quotes if your string contains spaces ** reverse( ) uses dynamic memory so any size string is ok */ #include <stdio. h> /* printf */ #include <stdlib. h> /* malloc, free */ #include <string. h> /* strlen, strcpy */ /* user error message */ #define USAGE "Usage: reverse "string to reverse in quotes"" /* prototype for reverse */ void reverse( char *s); 7/28/09
reverse. c - part 2 /* main checks the number of args ** then just calls the function to do the work */ int main(int argc, char *argv[ ]) { if (argc < 2) { printf("%sn", USAGE); exit(0); } char *string = argv[1]; reverse( string ); printf("%sn", string); return 0; } 7/28/09
reverse. c // void reverse (char[ ] s) void reverse( char *s ) { char *buf; int i, s. Length = strlen( s ); /* allocate memory -- why + 1 ? ? */ buf = (char *)malloc( s. Length + 1); /* copy string in reverse order in place */ for (i = 0; i < s. Length; i++) buf[i] = s[s. Length - i - 1]; buf[i]='