#include #include #include #define BUFLEN 24 int main(int argc, char *argv[]) { char buf[BUFLEN+1]; // +1 for the '\0' char* str; // this DOES NOT allocate space for a string char* comparisonOp[] = {"<", "==", ">"}; char** argP; int size; char* catResult; int cmpResult; // copy a string strcpy(buf, "test string"); // bug - is destination large enough? printf("buf = '%s'\n", buf); //strcpy(str, "test string"); // bigger bug - destination is 8 bytes! //printf("str = '%s'\n", str); // Duplicate a string str = strdup(buf); printf("dup'ed str = '%s'\n", str); // Compute result string length and concatenate strings size = 0; for (argP=argv; *argP; argP++) { size += strlen(*argP); } catResult = (char*)malloc(sizeof(char)*(size+1)); if ( catResult == NULL ) perror("string test main()"); catResult[0] = '\0'; // make buffer into a (null) string for (argP=argv; *argP; argP++) { strcat(catResult, *argP); // concatentate *argP on the end of string pointed at by catResult } printf("\nConcatenation result:\n%s\n", catResult); free(catResult); // Compare strings printf("\nComparisons:\n"); for ( argP=&argv[1]; *argP; argP++ ) { cmpResult = strcmp(*(argP-1), *argP); if (cmpResult < 0) cmpResult = -1; if (cmpResult > 0) cmpResult = 1; printf("%s %s %s\n", *(argP-1), (comparisonOp+1)[cmpResult], *argP); } return 0; }