Resizing char [] at runtime

I need to resize char array[size]at char array[new_size]runtime.

How can i do this?

+3
source share
6 answers

ok, thanks for all the answers, I fixed my problem by simply creating a new space for the new char throwght pointer array ... thanks

0
source

If you used std::vector<char>, not arrays, then the desired function will be just another method for this type.

+18
source

, char array[size] malloc 'ed.... realloc

( OpenBSD):

newsize = size + 50;
if ((newp = realloc(p, newsize)) == NULL) {
   free(p);
   p = NULL;
   size = 0;
   return (NULL);
}
p = newp;
size = newsize;
+6

.

+2

- :

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;
        }
};

- STL. , , ( STL ).

+2

, , :

char* array = (char*)malloc(sizeof(char) * number_of_chars_in_word);
0

Source: https://habr.com/ru/post/1716442/


All Articles