[prog] simple c++ question

Sue Stones suzo at bigpond.net.au
Mon Jun 23 17:14:39 EST 2003


On Mon, 23 Jun 2003 11:58 am, Jimen Ching wrote:
> On Sun, 22 Jun 2003, Laurel Fan wrote:
> >If you want to do it this way, you have essentially 2 choices:
> >
> >1. allocate the memory in main() first, then, in readText, copy the
> >tokenized string into your preallocated array.
> >
> >2. allocate the memory using malloc() in readText(), and set the
> >pointers to your allocated memory.
>
> 3. make tempText static in readText.  Of course, this will prevent using
> readText from multiple threads.  But strtok is not thread-safe either.  So
> using 'static' is ok.
>
> I should note, using <cstring> is not very object oriented nor C++.  The
> standard C++ library string class is very powerful, and has capabilities
> to do the things you want.  But I don't know the purpose behind using
> strtok and friends.  So I can't say if going straight OO is the correct
> path.
>
> --jc

Static memory works the same way in C++ as it does in Java.  It is called 
static because it is not dynamic, that is it is created at compile time an 
remains availabble for the duration of the program.  Using this method will 
mean that only one piece of memory will be alocated for tempText and text[j] 
will access bits of it.  

BUT if you call the function readText again it will write over the first line 
of text that is already present.    So if you are reading a file line by line 
and trying to keep the tokens from all lines this won't work.  If you just 
want to process info in 50 char bites at a time and then throw it away then 
static would be OK.

sue

ps remeber that Java is related to C++, so what you learnt there often still 
holds.  Looking for the differences is often easier than expecting it to be 
totally different.






More information about the Programming mailing list