Skip to content

Instantly share code, notes, and snippets.

@X140Yu
Created February 15, 2016 13:55
Show Gist options
  • Save X140Yu/95554385b377fe42785e to your computer and use it in GitHub Desktop.
Save X140Yu/95554385b377fe42785e 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: buffer to increse memory
* @buffer_size: the size of the buffer(pointer)
* Output: the double sized buffer
* 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(int argc, char *argv[])
{
// alloc memory for the initial buffer
char *buffer = (char *)malloc(INITIAL_BUFFER_SIZE * sizeof(char));
int input_ch;
int buffer_len = INITIAL_BUFFER_SIZE;
int char_len = 0;
int increase_time = 0;
// promote user to input
printf("Enter a string: ");
while((input_ch = getchar()) != '\n') {
if(input_ch == EOF) {
break;
}
if(char_len == buffer_len - 1) {
// not enough space, malloc memory
buffer = IncreaseBuffer(buffer, &buffer_len);
increase_time++;
}
buffer[char_len++] = input_ch;
}
// the strings should be end with '\0'
buffer[char_len] = '\0';
// some print
printf("String size: %d\n", char_len);
printf("Buffer increases: %d\n", increase_time);
printf("You entered: %s\n", buffer);
free(buffer);
return 0;
}
char* IncreaseBuffer(char* buffer, int* buffer_size) {
// malloc the memory for the new space
char *new_buffer = (char *)malloc(*buffer_size * 2 * sizeof(char));
*buffer_size *= 2;
// copy staff
char *head_new = new_buffer;
char *head_old = buffer;
while(*head_old != '\0') {
*head_new = *head_old;
head_old++;
head_new++;
}
// earse the old space
free(buffer);
return new_buffer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment