/*
Programmazione II - Esempio di codice
Example code: malloc demonstration. (20000724 prelz@mi.infn.it)
*/
#include
#include
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",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.\n",i+1,strings[i]);
}
/* Now suppose we want to clean the strings up. */
for(i=0; i