The idea is to write a function that reads string of unknown size from stdin
, keep it in dynamically allocated array of unknown size and return a copy of that array.
Is this the right approach? Could I be more clear? Would reading the input char-by-char be better than getting bigger chunks at once?
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char * read_string(void)
{
int buff_size = 11; /* size of temporary buffer */
char temp[11]; /* temporary input buffer */
char *output; /* pointer to allocated memory */
char *copy; /* copy of input string to be returned */
char *iterator; /* pointer to beginning of an array, used when searching for \n in input string */
output = malloc(10*sizeof(char)); /* allocates 10 bytes for first part of input */
if(output == NULL)
return NULL;
size_t size = 10*sizeof(char); /* keeps track of actual size of output */
//*output = '\0'; /* places NUL at the beginning of output, to make it empty string */
while(fgets(temp, buff_size,stdin) != NULL) /* read max 10 chars from input to temp */
{
strcat(output,temp); /* append read input to output, without \0 char */
if(strlen(temp) != 10 || temp[9] == '\n') /* if buffer wasn't full or last char was \n-stop because it reached the end of input string */
break;
size += buff_size - 1; /* if didn' reach end of input increase size of output*/
output = realloc(output,size);
if(output == NULL)
{
return NULL;
}
}
iterator = output; /* search for \n in output and replace it with \0 */
while(*iterator != '\n')
iterator++;
*iterator='\0';
copy=malloc(strlen(output) + 1); /* allocate memory for copy of output +1 for \0 char */
if(copy == NULL)
return NULL;
strcpy(copy, output); /* strcpy output to copy */
free(output); /* free memory taken by output */
return copy;
}
sizeof(char)
is 1 by definition, so multiplying by it is redundant. – busy_wait Sep 11 '13 at 12:06