I need to resize a char array[size]
to char array[new_size]
at runtime.
How can I do this?
I need to resize a char array[size]
to char array[new_size]
at runtime.
How can I do this?
You have to allocate a new array and copy the contents of the existing array to it. You can't simply make the existing array larger
If you were using std::vector<char>
rather than arrays, then the feature you want would be just another method on the type.
Something like this:
class HangUpGame {
char *palabra;
size_t palabra_size;
public:
HangUpGame(){
palabra = new char[DEFAULT_SIZE];
palabra_size = DEFAULT_SIZE;
}
virtual ~HangUpGame(){
delete [] palabra;
}
void Resize(size_t newSize){
//Allocate new array and copy in data
char *newArray = new char[newSize];
memcpy(newArray, palabra, palabra_size);
//Delete old array
delete [] palabra;
//Swap pointers and new size
palabra = newArray;
palabra_size = newSize;
}
};
In response to the comments on other answers, the best way to do this actually would be to use an STL container. But anyway, if you prefer to use arrays, it's quite easy to swap the current array with a bigger one (internally the STL containers will do exactly that anyway).
Delete the old array, if any, and then allocate a new one:
char* array = (char*)malloc(sizeof(char) * number_of_chars_in_word);
assuming char array[size]
was malloc
'ed....you can use realloc
example (taken from OpenBSD's man page):
newsize = size + 50;
if ((newp = realloc(p, newsize)) == NULL) {
free(p);
p = NULL;
size = 0;
return (NULL);
}
p = newp;
size = newsize;
ok, thanks for all the answers, I fixed my problem just by creating a new space for the new char array throwght a pointer... thanks