Skip to content

Instantly share code, notes, and snippets.

@X140Yu
Created February 15, 2016 14:17
Show Gist options
  • Save X140Yu/3e8268f57b2a167896fe to your computer and use it in GitHub Desktop.
Save X140Yu/3e8268f57b2a167896fe to your computer and use it in GitHub Desktop.
/*
* 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment