Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- const int DEFAULT_STRING_LENGTH = 30;
- const int REALLOC_FACTOR = 1.5f;
- //vergleicht, ob die größe eines arrays über max_size liegt und erweitert speicher dementsprechend
- char* check_size_and_realloc(char* array, int max_size, int array_size)
- {
- //es ist wahrscheinlicher, dass ein eingegebener string, der sowieso schon relativ lange ist, noch einmal um ein ganzes stück anwächst,
- //als dass er um eine konstante größe anwächst (z.B. +10). diese wahrscheinlichkeit erhöht sich noch weiter, je länger der string wird.
- //Deswegen wird hier die array größe um einen faktor REALLOC_FACTOR verfielfacht, anstatt die größe nur um eine konstante zu erhöhen
- return max_size == array_size ? realloc(array,array_size*REALLOC_FACTOR) : array;
- }
- //Liest einen beliebig langen String aus stdin und liefert ihn zurück.
- char* get_str()
- {
- char* string = malloc(sizeof(char)*DEFAULT_STRING_LENGTH);
- char next_typed_char;
- int array_size = 0;
- int total_typed_chars;
- for(total_typed_chars=0; (next_typed_char = getchar()) != '\n'; ++total_typed_chars)
- {
- string[total_typed_chars] = next_typed_char;
- ++array_size;
- //falls buchstaben mehr werden als array_größe, array erweitern
- string = check_size_and_realloc(string,total_typed_chars,array_size);
- }
- //Schauen, ob noch Platz fürs \0 is
- string = check_size_and_realloc(string,++total_typed_chars,array_size);
- string[total_typed_chars] = '\0';
- return string;
- }
- int main(int argc, char** args)
- {
- char* string = get_str();
- printf("%s",string);
- free(string);
- return 0;
- }
Add Comment
Please, Sign In to add comment