Originally posted by Hammer
- Use a buffer that is long enough to hold all input.
- Once a string is in the buffer, determine it's length
- malloc() memory to hold that many bytes (plus 1 for the null terminator)
- string copy from the buffer to the new memory.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 50
#define NUMBER_OF_STRINGS 5
int main(void)
{
char buffer[MAX_LENGTH];
char *ip[NUMBER_OF_STRINGS];
int len, i;
for (i = 0; i < NUMBER_OF_STRINGS; i++)
{
printf ("Enter String number %d: ", i);
if (fgets(buffer, MAX_LENGTH, stdin) == NULL)
ip[i] = NULL;
else
{
len = strlen(buffer);
if (buffer[len-1] == '\n') buffer[len-1] = '\0', len--;
if ((ip[i] = malloc(len+1)) == NULL)
{
perror ("malloc");
return (1);
}
strcpy (ip[i], buffer);
}
}
for (i = 0; i < NUMBER_OF_STRINGS; i++)
{
if (ip[i] != NULL)
{
printf ("String %d is: >%s<\n", i, ip[i]);
free(ip[i]);
}
}
return (0);
}