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

Asked

Viewed 634 times

3

My question is about the theory.

I know it’s possible to make a string without limiting the size of the:

char teste[] = "Teste";

however, I would like to know if it has how to do the same thing, ie not limiting the size, but not talking about what I want inside and yes leaving the scanf() limit.

1 answer

7


Actually the question starts from the wrong premise. The code that creates the string There’s nothing limitless 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 that region. You can’t change that size.

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

In any case there will be a size limit. It has no different.

The scanf() let you write as much as you want in memory, this is even one of the criticisms made of it. It just doesn’t mean that the memory won’t be corrupted.

What you can do is read character by character and relocate the memory. I made a naive implementation in another response. An improvement there would be to go doubling in size each relocation and already start with a reasonable size, this would make the complexity logarithmic. I mean, write your own scanf().

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.