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 doubles, 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

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

javascript - addthis share facebook and google+ url -

ios - Show keyboard with UITextField in the input accessory view -