X140Yu
2/15/2016 - 2:17 PM

02-get_string.c

/*
 * get_string.c
 *
 *
 * Read a string from stdin,
 * store it in an array,
 * and print it back to the user.
 */

#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>

#define INITIAL_BUFFER_SIZE 16

/*
 * Input:
   buffer to realloc and its size
 * Output:
   the buffer doubled
 * Summary:
   This function doubles the capacity of your buffer
   by creating a new one and cleaning up the old one.
 */
char* IncreaseBuffer(char* buffer, int* buffer_size);

int main()
{
    char *mainBuffer = (char*)malloc(INITIAL_BUFFER_SIZE*sizeof(char));
    int getedChar;
    int bufferLength = INITIAL_BUFFER_SIZE;
    int stringSize = 0;
    int increases = 0;
    printf("Enter a string: ");
    while((getedChar = getchar()) != '\n') {
        if(getedChar == EOF) {
            break;
        }
        if(stringSize == bufferLength - 1) {
            mainBuffer = IncreaseBuffer(mainBuffer, &bufferLength);
            increases++;
        }
        mainBuffer[stringSize++] = getedChar;
    }
    mainBuffer[stringSize] = '\0';
    printf("String size: %d\n", stringSize);
    printf("Buffer increases: %d\n", increases);
    printf("You entered: %s\n", mainBuffer);
    free(mainBuffer);

    return 0;
}

char* IncreaseBuffer(char* buffer, int* buffer_size)
{
    char* newBuffer = (char*)malloc(*buffer_size*sizeof(char)*2);
    char* newStart = newBuffer;
    char* oldStart = buffer;
    while('\0' != *oldStart)
    {
        *newStart++ = *oldStart++;
    }
    *buffer_size *= 2;
    free(buffer);
    return newBuffer;
}