Quote:
Originally Posted by kyle4579
but I don't fully understand the coding which precedes the main function...! Would you have time to go over it briefly, please? Thanks for the help so far though, much appreciated.
|
first, check manpages for malloc, free and realloc. (man malloc, etc.).
And I think reading books on C++ and practice (and a lot of it) will help more than my explanation. If you love programming (this is required) then you'll get all concepts eventually during practice.
Also, you'll get much better answers
if you'll point out which parts you don't understand. I can't cover pointers, basic constructs like resizeable arrays, memory allocation functions, etc. in one post. (it's all explained in books).
Brief description:
generally variable/function names speak for themselves.
"char* arrayData = 0"
A
pointer ("address") to the the memory block where we hold chars we've read. You may think about it as array with dynamic size, or the address of the array. Block is initialized with malloc (see "man malloc"), and freed with "free" (all allocated memory must be freed to prevent memory leaks). Realloc() changes size of block we've allocated, but preserves all existing data.
"int arraySize = 0;"
tells how many elements in array right now.
"int arrayCapacity;"
tells how many elements dynamic array can hold.
If we allocate block for 32 chars and then try to write 33th char, then we'll get segfault (if we are lucky. If we aren't (on old compilers, etc, real-mode systems, etc.), then it'll overwrite some memory region nearby, and we'll spend eternity trying to figure out "why things doesn't work as expected").
"void initArray(){"
function that initializes array. Sets that array can hold 32 elements and allocates block of that size.
"void growArray(){"
called when arraySize is equal to capacity - i.e. no more chars can be placed in our memory block. Sets it so array can hold 2x more elements then before and reallocates memory block according to new capacity.
"void appendChar(char c){"
appends char to array, changes number of elements accordingly, checks if array need to grow.
Can't explain much more, you'll get better answers if you ask what exactly you don't understand.