Nic*_*ick 1 c++ heap-memory visual-c++
有没有办法创建一个函数,可以将一块内存分配到堆上,调用者可以传递一个他们想要分配的大小并返回一个有效的地址供调用者使用?我知道如何分配特定的大小,但有没有办法让呼叫者通过所需的金额?
绝对:即使在Ç malloc/ calloc/ realloc一切以大小作为他们的参数,他们不在乎这种规模是从哪里来的; 同样的new.
例如,如果要分配用户指定的doubles 数,则执行以下操作:
cout << "Enter the number of double elements that you want to allocate" << endl;
int count;
cin >> count;
// You can do this for C-style allocation...
double *chunkMalloc = malloc(sizeof(double)*count);
// ...or this for C++ style:
double *chunkNew = new double[count];
// Don't forget to free allocated chunks:
free(chunkMalloc);
delete[] chunkNew;
Run Code Online (Sandbox Code Playgroud)