Page 2 of 2

Re:The C pro

Posted: Sat Oct 23, 2004 2:54 pm
by mystran
Actually, since the text that the program gets as input is not known (especially it's length), it is not possible to allocate memory statically and have it accept text of arbitary length.

There are two ways to get around this problem:
- Read the text in parts, process each part at a time before reading the next part.
- Allocate dynamically a buffer of certain length, read data into it (with a limit), if data didn't fit, allocate larger buffer, move the old data in the new buffer, and new data to the rest of the buffer. If it still doesn't fit, resize again. Calculate the size of the buffer with F*old_size where F is some constant (values like 1.5 or 2 are usually good), and you get average constant time per character.

When you initialize as "char a[20]" exactly 20 bytes are reserved (or so you should assume) so you can fit 19 characters plus the ending 0 into that array.