How to read unlimited characters into a char*
variable without specifying the size?
For example, say I want to read the address of an employee that may also take multiple lines.
How to read unlimited characters into a char*
variable without specifying the size?
For example, say I want to read the address of an employee that may also take multiple lines.
Just had to answer Ex7.1, pg 330 of Beginning C, by Ivor Horton, 3rd edition. Took a couple of weeks to work out. Allows input of floating numbers without specifying in advance how many numbers the user will enter. Stores the numbers in a dynamic array, and then prints out the numbers, and the average value. Using Code::Blocks with Ubuntu 11.04. Hope it helps.
You have to start by "guessing" the size that you expect, then allocate a buffer that big using
malloc
. If that turns out to be too small, you userealloc
to resize the buffer to be a bit bigger. Sample code:This is just off the top of my head, and might (read: will probably) contain errors, but should give you a good idea.
How about just putting a 1KB buffer (or 4KB) on the stack, reading into that until you find the end of the address, and then allocate a buffer of the correct size and copy the data to it? Once you return from the function, the stack buffer goes away and you only have a single call to
malloc
.