c++ - How to allocate memory on the heap via user input? -
is there way create function can allocate chunk of memory onto heap caller can pass size want allocate , return valid address caller use? know how allocate specific size there way have caller pass desired amount?
absolutely: in c malloc
/calloc
/realloc
take size parameter, , not care size came from; same goes new
.
for example, if allocate user-specified number of double
s, this:
cout << "enter number of double elements want allocate" << endl; int count; cin >> count; // can c-style allocation... double *chunkmalloc = malloc(sizeof(double)*count); // ...or c++ style: double *chunknew = new double[count]; // don't forget free allocated chunks: free(chunkmalloc); delete[] chunknew;
Comments
Post a Comment