简体   繁体   English

如何通过用户输入在堆上分配内存?

[英]How to allocate memory on the heap via user input?

Is there a way to create a function that can allocate a chunk of memory onto the heap where a caller can pass a size that they want to allocate and return a valid address for the caller to use? 有没有一种方法可以创建一个可以在堆上分配内存块的函数,调用方可以在该堆上传递要分配的大小,并返回有效地址供调用方使用? I know how to allocate a specific size but is there a way to have a caller pass the desired amount? 我知道如何分配特定大小,但是有没有办法让呼叫者通过所需的金额?

Absolutely: even in C malloc / calloc / realloc all take the size as their parameter, and they do not care where that size came from; 绝对:即使在C malloc / calloc / realloc都将大小作为其参数,并且它们并不关心该大小来自何处; same goes for new . new

For example, if you would like to allocate a user-specified number of double s, you do this: 例如,如果您要分配用户指定的double数,请执行以下操作:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM