Home c Dynamic memory allocation in SI

Dynamic memory allocation in SI

Author

Date

Category

The question will seem probably simple, but not for me. Size is unknown in advance, it all depends on the user’s desire.
Structure Announcement:

struct book * Books;

then, if a person wants, he can create another 1 book, I highlight the memory for it in such a way:

Books = (Struct Book *) Malloc (SizeOF (Struct Book));

But as I understand it, I do not add another place to memory, but only I finish and identify a new memory, so I can only have 1 book in the structure. How to add place in memory as it is added 1 book? It is not optimal to declare in advance, because we do not know how much you need to add, everything is solved in the prime time.

Or is everything solved by the announcement of the struct book ** books?


Answer 1, Authority 100%

To redistribute memory, try using realloc ().
https://ru.cppreference.com/w/cpp/memory/c/ realloc


Answer 2

realloc Use in this case is not an option, as what it does – it highlights a dynamically greater place in memory, then copies the data and the previous smaller place, and then clears then less. Imagine you already are busy 1 GB of Pammayti and you make a realloc on 1 GB + 1 byte. In this case, you will need to highlight 1 GB + 1 bytes, copy 1 GB and clean 1 GB. Very not productively!
In two cases, it is necessary to implement an abstract data type list , single-connected or doubled. You can use ready-made solutions from many libraries (GLIB for example) or write it yourself, turning on the operation of creating a list, adding an item, delete an item and search for an item. Each elements of the SPMSK will be as data to contain a pointer to the allocated so much dynamically memory under the structure of the book with information about it.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions