On Feb 13, 2:00 am, John Harrison <john_androni...@hotmail.comwrote:
whitehatmira...@gmail.com wrote:
Hi all
Im not quite sure how to use the new and delete for a whole array
dynamically.
Actually i want that, a user inputs a char in a single char array.
Everytime he inputs a char he creates a new array of (previous size +
1), he then copies the content of the old array in to the new array
and adds the new input at the end and deletes the old array. I guess
he has to pass the pointer to the array everytime.
For example.
input: a
output a
input: b
output: a b
input c:
output a b c .
Any clues??????????????
char* array = new char[sizeof_of_array];
delete[] array;
But Andre is right use std::vector or std::string. Forget memory
allocation details and learn how to program.
Wellll.....not quite. Having a firm grasp on memory allocation/
deallocation is a Good Thing (TM) to have in *any* programming
language. Yes, even if that language is garbage collected and you
never have to worry about the specifics.
You don't necessarily need to learn the finer details of memory paging
and cache hits vs misses but being able to write a function that is
capable of dynamically reallocating an array is IMHO something that
every programmer should know regardless of language. If you lose sight
of things like this you won't realize why your program is leaking
copius amounts of memory and you'll end up with bad software.
That little tirade out of the way, once you learn enough about memory
allocation/deallocation/reallocation using classes like std::vector or
std::string is great and even recommended. They save you the time of
writing those classes yourself. They're *thouroughly* tested and
stable. All signs of good code.
john
Back to the original posting though,
Im not quite sure how to use the new and delete for a whole array
dynamically.
Syntax for new'ing an array is like this:
int array[] = new int[array_size] ;
Syntax for deleting an array is like:
delete [] array ;
I guess
he has to pass the pointer to the array everytime.
Well, if you're not passing the array into the method somehow
( explicit argument, member variable of a class, etc ) you're going to
have a hard time modifying it.
A non-C++ method signature for doing something like this would be:
int
add_member( char array[], int current_size ) ;
In 'real' C++ this would be accomplished using a std::vector or some
other container as mentioned.
HTH,
Paul Davis