Skip to main content
gamedev.net
🔒 Locked

Pointer question.

Started by disanti Nov 21, 2004 at 10:27 AM 3 replies 650+ views
Original Post
disanti
disanti
Is it possible to reallocate a pointer? Example: char* string = new char[100]; strcpy(string, otherthing); string = new char[300]; If I were to do that, when I reinitialized it, would it keep the old values or erase them? Would it even compile? Thanks, I didn't feel like searching today. ~ John DiSanti
My game development blog: http://rykerlabs.com
Ra
Ra
The first assignment will allocate 100 characters and store the pointer in string. The second assignment will allocate 300 characters and store that pointer in string. It will not contain the same data; new is like a malloc call. You'd also want to free that memory before you call new again, because it won't be deallocated (creating a memory leak).
Ra
twanvl
twanvl
This will compile, but it doesn't work, your old values will be lost and the program will leak memory. There are two possible solutions.
Use realloc, you should only do this in C style code
char* string = (char*)malloc(100);strcpy(string, otherthing);string = (char*)realloc(string,300);

Use a std::string (for strings) or a std::vector (for lists of other objects):
std::string string = otherthing;string += "make it longer"; // string will grow automaticly
RPTD
RPTD
you will produce a memory leak with this. if you call new you create a memory chunk. you then just store a pointer to it in your variable. you need to delete that pointer first before you can assign a newly create memory chunk to this variable or your memory chunk starts floating around cluttering memory.

with new/delete you can not relallocate memory. so you need to:
- create a new memory
- story it temporary (in another variable)
- copy things over
- free old memory pointer
- move pointer from temporary variable into old variable
Life's like a Hydra... cut off one problem just to have two more popping out.
Leader and Coder: Project Epsylon | Drag[en]gine Game Engine
Aprosenf
Aprosenf
char *string = new char[100];strcpy(string, otherthing); char *temp = new char[300]; strcpy(temp, string); delete [] string; string = temp;temp = NULL;


string is now longer and contains the original data, and there are no memory leaks (assuming you delete [] string at the end of your program and you're done).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.