How can I input data using scanf() and char *string;
char * string; // char pointer
char str; // char array
scanf("%s",string); // input on this adrees, not work
scanf("%s",str); // input from first addreess , work
I don't want to write bordered array , I want it would include exact number of text's symbols.
If you use C++ you don't need to worry about string size, just use std::string and it will automatically adjusts its buffer size to fit the input.
If you use C then I'm not sure how you can deduce the input length to allocate exact number of bytes needed to store the input. But perhaps there will be others having more experience who knows how to do that.
" scanf("%s",str); // input from first addreess , work "
This line still puts your program in the danger of stack overflow (stack corruption) due to the use of unspecified width for `%s` specifier.
With a buffer as `char str;` you must specify at most `9` chars width to trim the longer inputs + preserving a single char for '\0' (null terminator) like so
str = '1'
str = '2'
str = '3'
str = '4'
str = '5'
str = '6'
str = '7'
str = '8'
str = '9'
str = '\0'
What you have described Dave Smith is a big reason why scanf is so hated in the C community. A solution I tend to work with is to dynamically reallocate the size of the array to continue reading until I hit a newline, eof, and/or null terminator.
Usually I have a better idea of what the maximum amount of characters my code reads in and do my resizing and rereading based on that.
Like if I know I am only required to read in 1024 characters ± a null terminator, I will base my reads around that, reallocating as efficiently as I can (as reallocating + reads are expensive processes).
Furthermore you should look into alternatives to scanf. Some methods allow you to read in a number of bytes at a time (like fgets), others allow you to read a number of characters in at once and then you just check if there is more to be read, and if there is and you need more space, reallocate for it.
trouble is that “string” doesn’t have any space allocated to it. scanf doesn’t do any buffer checking. if you typed 20 characters into a variable with inly 10 allocated, you end up with big problems, (buffer overflow). There’s a whole thread, and more, on bad C functions: https://stackoverflow.com/questions/1253053/cs-bad-functions-vs-their-good-alternatives
Scanf() is a way to manipulate memory, i am studying that stuff at the moment. No one should use scanf()
Even printf() can be exploitet, if you can access the memory.
Its really exiting to do that. Maybe play a little bit on your computer with scanf. I could overflow that stuff and run a sudo command after that. That's so funny.