Reallocating a char *

  • Thread starter Thread starter Abubakar
  • Start date Start date
A

Abubakar

Hi,

(all unmanaged c++)

I have a char *. I allocate it using:
char * t = new char [ any_size_here];

at some point I want its length to grow to accomodate copying more
characters. What is the best way of doing it?
Also, can I just use std:string instead, and is its string appending very
efficient?

regards,

Ab.
 
(all unmanaged c++)
I have a char *. I allocate it using:
char * t = new char [ any_size_here];

at some point I want its length to grow to accomodate copying more
characters. What is the best way of doing it?
Also, can I just use std:string instead, and is its string appending very
efficient?

You would have to allocate a new piece of memory that is bigger than the
first one, copy over the data and then delete the first block.

My experience with std::string has been very positive. It has always been
fast enough for me, and it has the advantage that you don't have to worry
about all those allocations and deallocations yourself. It is also well
documented.

I would definitly advise you to use it, and not roll your own unless you
have a very specific need that is not addressed by the std::string
solutions.

--

Kind regards,
Bruno van Dooren
(e-mail address removed)
Remove only "_nos_pam"
 
Abubakar said:
Hi,

(all unmanaged c++)

I have a char *. I allocate it using:
char * t = new char [ any_size_here];

at some point I want its length to grow to accomodate copying more
characters. What is the best way of doing it?
Also, can I just use std:string instead, and is its string appending very
efficient?

regards,

Ab.
You probably know that arrays cannot be resized, so you'll need to do
something like this...

char* u = new char[new_bigger_size];
// strncpy() loop to save existing data in *t to *u
delete [] t;

What Bruno said about the string class! Gives you all sorts of flexibility
and useful features, and performs well IME.
 
Thanks all,

Ab.


Bruno van Dooren said:
(all unmanaged c++)

I have a char *. I allocate it using:
char * t = new char [ any_size_here];

at some point I want its length to grow to accomodate copying more
characters. What is the best way of doing it?
Also, can I just use std:string instead, and is its string appending very
efficient?

You would have to allocate a new piece of memory that is bigger than the
first one, copy over the data and then delete the first block.

My experience with std::string has been very positive. It has always been
fast enough for me, and it has the advantage that you don't have to worry
about all those allocations and deallocations yourself. It is also well
documented.

I would definitly advise you to use it, and not roll your own unless you
have a very specific need that is not addressed by the std::string
solutions.

--

Kind regards,
Bruno van Dooren
(e-mail address removed)
Remove only "_nos_pam"
 
Back
Top