/* Programmazione II - Esempio di codice Example code: malloc demonstration. (20000724 prelz@mi.infn.it) */ #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { char input[800]; /* The only way to avoid this is to input one character at a time.... */ int nstrings; int i; char **strings; printf("How many strings would you like to enter? ---> "); fgets(input, sizeof(input), stdin); nstrings = atoi(input); if (nstrings <= 0) exit(0); strings = (char **)malloc(nstrings*sizeof(char *)); if (strings == NULL) { fprintf(stderr,"Out of memory!\n"); exit(1); } for (i=0; i<nstrings; i++) { printf("Please enter string n.%d --->",i+1); fgets(input, sizeof(input), stdin); /* Get rid of trailing newline */ if (input[strlen(input)-1] == '\n') input[strlen(input)-1] = '\000'; strings[i] = (char *)malloc(strlen(input)+1); if (strings[i] == NULL) { fprintf(stderr,"Out of memory!\n"); exit(1); } strcpy(strings[i], input); } for(i=0; i<nstrings; i++) { printf("String n. %d is <%s>.\n",i+1,strings[i]); } /* Now suppose we want to clean the strings up. */ for(i=0; i<nstrings; i++) { free(strings[i]); } free(strings); exit(0); }