search

Home  >  Q&A  >  body text

c++可以实现使用new分配内存后,再增加内存吗?

#include <iostream>
#include <cstring>
#include <string>

using namespace std;

int main()
{

    char* arr = new char('A');
    cout << *arr << endl;
    return 0;
}

现在arr指向的内存空间只有一个'A',可不可以直接拓宽这个内存空间的大小,还保留这个内存空间中的数据。如果是重新使用arr = new char[10]这样的话,应该是直接改变了arr指向的内存地址吧,可不可以实现拓宽原arr指向地址的空间大小,还保留着原来的数据'A'呢?

巴扎黑巴扎黑2804 days ago575

reply all(4)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 13:52:02

    There are many methods, here are two:

    1. Use memcpy manual movement data:

    char* arr = new char('A');
    char* new_mem = new char[10];
    memcpy(new_mem, arr, sizeof(*arr));
    delete arr;
    arr = new_mem;
    ... 
    // 最后回收内存要用 delete [];
    delete []arr;
    1. Do not use new in the whole set, replace it with malloc, realloc:

    char* arr = malloc(sizeof(char));
    *arr = 'A';
    
    char* new_mem = realloc(arr, sizeof(char[10]));
    arr = new_mem;
    
    // 最后清理内存用 free
    free(arr);

    reply
    0
  • 阿神

    阿神2017-04-17 13:52:02

    The C++ approach should be to use vector to deal with the dynamic demand for memory like this:
    vector<char> arr;
    arr.push_back('A');

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 13:52:02

    The method mentioned by @casheywen is correct, but it is best to use it in C. C++ will not guarantee that the memcpy operation is successful for the object. It is best to use the copy constructor to copy the object. Because there are POD data and non-POD data in C++, the non-POD data compiler will insert the virtual table pointer into it, so the memory layout may not be completed directly using memcpy copy. In other words, even if it is copied, it may still be running. Undefined behavior may occur and cause the program to crash.
    POD
    http://blog.csdn.net/bichenggui/article/details/4719363

    There is also a memmove method, see here
    http://www.jb51.net/article/56012.htm

    Regarding non-POD operations, you may have to wait for a long time to use C++ to find out. This is a runtime insecurity. The code is not necessarily guaranteed to crash, but it will crash in some cases

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 13:52:02

    1. It is not possible to widen the space size of the address pointed by the original arr.

    2. When a new space is opened, the address will definitely change.

    3. As for retaining the original content, just copy it.

    reply
    0
  • Cancelreply