/* * Some C-idioms on how-to do common operations * * I used strspn, strcpn, and strncpy from the library * You could "role your own" for those, if you want to get * more experience with pointer. */ #include #include #include #define MAXWORD 80 #define MAXLINE 20 char * myStrCpy(char * src, int size); int main(int argc, char **argv) { /* allocating a 2-dimensional array of strings. */ char **myargv; char ibuf[MAXWORD]; char *p; int size, i=0; if ((myargv = (char **) malloc(MAXLINE * sizeof(char *))) == NULL) { printf("Error allocing the myargv array\n"); exit(-1); } while (p = fgets(ibuf, MAXWORD, stdin)) { /* parse the line, assume blank or tab as word separator */ while (*p ) { p += strspn(p, " \t"); /* skip whitspace */ size = strcspn(p, " \t"); /* size of the word */ myargv[i++] = myStrCpy(p, size); /* copy the word */ p+=size; } } myargv[i] = NULL; i = 0; while (myargv[i]) { printf("string %d: %s\n", i, myargv[i++]); } } char * myStrCpy(char * src, int size) { char *p; if ((p = malloc(size+1)) == NULL) { printf("Error allocing the string array \n"); exit(-2); } strncpy(p, src, size); *(p+size) = '\0'; return p; }