This commit is contained in:
Miloslav Ciz 2023-09-10 13:29:33 +02:00
parent 9cfc9e6d64
commit cf33ea2de9
5 changed files with 25 additions and 11 deletions

View file

@ -1609,17 +1609,14 @@ int main(void)
{
int charsRead = 0;
int resized = 0; // how many times we called realloc
char *inputChars = malloc(ALLOCATION_CHUNK * sizeof(char));
char *inputChars = malloc(ALLOCATION_CHUNK * sizeof(char)); // first allocation
while (1) // read input characters
{
char c = getchar();
charsRead++;
if (c == '\n')
break;
if ((charsRead % ALLOCATION_CHUNK) == 0)
{
inputChars = // we need more space, resize the array
@ -1628,12 +1625,18 @@ int main(void)
resized++;
}
inputChars[charsRead] = c;
inputChars[charsRead - 1] = c;
if (c == '\n')
{
charsRead--; // don't count the last newline character
break;
}
}
puts("The string you entered backwards:");
while (charsRead > 1)
while (charsRead > 0)
{
putchar(inputChars[charsRead - 1]);
charsRead--;
@ -1648,7 +1651,7 @@ int main(void)
}
```
This code reads characters from the input and stores them in an array (`inputChars`) -- the array is dynamically resized if more characters are needed. (We restraing from calling the array `inputChars` a string because we never terminate it with 0, we couldn't print it with standard functions like `puts`.) At the end the entered characters are printed backwards (to prove we really stored all of them), and we print out how many times we needed to resize the array.
This code reads characters from the input and stores them in an array (`inputChars`) -- the array is dynamically resized if more characters are needed. (We restrain from calling the array `inputChars` a string because we never terminate it with 0, we couldn't print it with standard functions like `puts`.) At the end the entered characters are printed backwards (to prove we really stored all of them), and we print out how many times we needed to resize the array.
We define a constant (macro) `ALLOCATION_CHUNK` that says by how many characters we'll be resizing our character buffer. I.e. at the beginning we create a character buffer of size `ALLOCATION_CHUNK` and start reading input character into it. Once it fills up we resize the buffer by another `ALLOCATION_CHUNK` characters and so on. We could be resizing the buffer by single characters but that's usually inefficient (the function `malloc` may be quite complex and take some time to execute).