How to let the string size be set by scanf ()?

2

My question is about theory.

I know it's possible to do a string without limiting its size as:

char teste[] = "Teste";

However, I would like to know if you can do the same thing, that is, not limiting the size, but without saying what I want inside it, but leaving scanf() limit.

    
asked by anonymous 23.08.2017 / 19:37

1 answer

5

In fact the question starts from the wrong premise. The code that creates the string is limiting it to 5 characters, there is nothing unlimited there. This code will reserve 6 bytes in the code to allocate the 5 characters plus the terminator and at the time the function is called a pointer will be allocated to this region. You can not change that size.

What can be done is to create a completely different string , allocated in the static part of the code like this of the code, allocated in heap dynamically or automatically stack , and the address where that new string can be placed in the variable teste .

In any case there will be a size limit. There is no way to be different .

scanf() lets you write as much as you want in memory , this is up to one of the criticisms that does it to him. It just does not mean that the memory will not be corrupted.

What you can do is read character by character and go by relocating the memory. I made a naive implementation in another answer . One improvement there would be to double-size each reallocation and to start with a reasonable size, this would make the logarithmic complexity. That is, write your own scanf() .

Read What are and where are the stack and heap? .

    
23.08.2017 / 19:58