How to allocate more memory for a buffer in C ++?

I have a pointer str:

char* str = new char[10];

I use a memory block strto store data.

How can I allocate more bytes for the buffer pointed strto and not lose the old data stored in the buffer?

+3
source share
8 answers

Use std :: string instead . It will do what you need without worrying about distribution, copying, etc. You can access raw memory with the c_str () function.

It will even work well for you. std::vector<char>

+17
source

new[] , ( memcpy()), delete[] , , .

+8

new. malloc, realloc free ( malloc/realloc/free new/delete).

+3

++, std::vector. , , std::string ( std::vector, ). 10 . , , , , 10 , , , . , , . , , , , , , .

int main()
{
    std::string s;
    s.reserve( 10 );
    // do whatever with s
}

, std::string std::Vector , .

+1

realloc - , . malloc/free new/delete,

0

str .

0

realloc: http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/ , ++ ( , , , std::vector<char>).

0

. , , .

: C , realloc, . , , . , , .

, .

, ? , , , , , . , , .

, STL. -, "". std::string, , .

0

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


All Articles