A
A
alex4answ2019-01-24 13:57:30
C++ / C#
alex4answ, 2019-01-24 13:57:30

How to correctly change the size of the allocated memory?

Good afternoon, there is a task:
Implement the getline function, which will read the input character-by-character and return the C-style string.
the initial signature of the function is given: And here is another question along the way) Is the function supposed to return a string, and not a pointer to it? Well, in general, the main question is: I know how to allocate memory, there seems to be no problem with this, but initially we don’t know how many characters will be given, it turns out we need to read and re-allocate memory, right? Isn't it too "expensive"? I know how to allocate memory in the C and C++ style. In C there is realloc - which will change the size of the allocated memory itself , but not in the C++ style. If I allocate memory:
char *getline();
new [], then in order to resize, I need to remove it with delete[] and allocate a new one with a larger size, right?
And it turns out that in order to implement the necessary function (count character-by-character input and return a C-style string), it will be necessary to delete the allocated memory and create more, and so on with each new character, until we reach the end?
So far, it seems to me that this is some kind of very strong crutch, and it’s easier to use realloc because it will do everything on its own

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2019-01-24
@alex4answ

There are no strings per se in C - a string is an array of bytes with a terminating null byte at the end.
An array in C is a pointer.
In C++, use string - that's what they invented it for, so that it doesn't take a steam bath in every application with similar things.
If purely in C, then for each character, of course, it is not profitable to pull the memory, so allocate memory in chunks.
For example - set a fixed initial buffer size and increment size. Often, instead of incrementing, the buffer size is doubled. The strategy may be different. For simple applications, it is generally possible to allocate a fixed buffer size (large enough) and not re-allocate memory.
Don't forget to manually insert a null byte at the end of the string to mark the end of the string. The end of the string does not have to match the end of the buffer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question