Arrays with dynamic memory allocation. | Sololearn: Learn to code for FREE!

+7

Arrays with dynamic memory allocation.

Can anyone please provide me "c++" code in which the size of the array determines according to the user input by dynamic memory allocation? For example: Input: 1 2 3 4 5 Output: Size of the array : 5 Basically,1,2,3,4,5 ought to be stored in int array and that array size should be print.

c++

5/23/2022 3:26:35 PM

Manav Roy

12 Answers

New Answer

+4

// Like "ENEMY enemies[100]", but from the heap ENEMY* enemies = malloc(100 * sizeof(ENEMY)); if (!enemies) { error handling } // You can index pointers just like arrays. enemies[0] = CreateEnemy(); // Make the array bigger ENEMY* more_enemies = realloc(enemies, 200 * sizeof(ENEMY)); if (!more_enemies) { error handling } enemies = more_enemies; // Clean up when you're done. free(enemies);

+3

What you're looking for is a dynamic array, whose equivalent in the C++ STL is std::vector https://m.cplusplus.com/reference/vector/vector/

+3

Manav Roy https://www.sololearn.com/learn/261/?ref=app

+3

Manav Roy Then I think you should not get into problems like these for now. It's not like it's very complicated, in fact, a dynamic array is a very simple structure, but I think you should know the language you're using first. I say this because there isn't a specific way of making a dynamic array in C++ due to there being no standard way to reallocate memory. So you have to reply on C functions which are generally less preferred to the 'new' and 'delete' operators. Here is a solution to your problem if you're still interested, but std::vector should be the preferred way of doing this https://code.sololearn.com/c112t9UIu30K/?ref=app

+2

this is dynamic memory allocation.. int size; cin>>size; int* arr= new int[size]; for(int i=0;i<size;i++) cin>>arr[i] Hope it will be helpful for you 😇

+1

Ulysses Apokin I'm not getting the proper usage of realloc in the case of getting the size according to user input. How do we know that how many blocks do we've to create? (Like it's 200 in your case in realloc)

+1

You can create a do-while loop. Place a counter in this loop. Make the numeric value of the counter an argument to the realloc function.

+1

XXX No, I've not even completed OOPs.

0

Ulysses Apokin I've not studied vector yet :(

0

Muhammad Yasin Hello,In this code , We're specifying the size of the array first via user input. This could also be done by static memory allocation. I want that user should enter any xyz input, And the size of the array should print.

-2

?idk? https://code.sololearn.com/W00tVslTshYw/?ref=app

-3

Sorry