New instead of malloc(), -?- instead of _expand() & realloc() ?
What function am I suppoused to use instead of _expand() and realloc() when trying to allocate more memory for the same variable?
If you''re using new/delete, there isn''t a direct method. What you have to do is create a new allocation, copy the data appropriately, and delete the old one. For example:
char *p = new char [10]; // p points to an array of 10 chars...// oh no, now we need 20 chars! OK....char *ptemp = new char [20]; // create a 20-char arraystrcpy(ptemp, p); // copy in pdelete [] p; // free the old, unneeded memoryp = ptemp; // and reset p to point to the 20-char array
quote:Original post by BriTeg
strcpy(ptemp, p); // copy in p
[/source]
And what if the array contains something else than a string?
AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.
quote:Original post by Arild Fines
And what if the array contains something else than a string?
He probably meant memcpy(). I don't use either of those functions myself, since there is std::copy().
[edited by - antareus on May 29, 2003 8:40:02 AM]
I meant memcpy, because I was thinking a nul-terminated string in my example (hence the char *). But yes, memcpy for non-string, but then you have to also supply the number of bytes you want copied. std::copy is also good, if you''re a namescope type of person. I work with a lot of legacy code where stuff like this isn''t used, so I often forget about it.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement