The problem in this program is that if I insert 1 for N and then
insert name who had more letters than that we entered on start. Why
this works and I get the full name?
The reason why it (in your case) works is called "Undefined Behavior". You can´t expect/guarantee anything if you insert such issues in your program. It is possible that the right values appear but high-probably on another implementation you will get completely different results. Always and ever avoid the likes of those and program in the right way with a clean-focus on what you actually do.
Here a link for more informations about what UB is: Undefined, unspecified and implementation-defined behavior
how to convert a char
into int
so if the user insert number for
how much letter he have in his name, and later insert a name with
more letters, I can print "Error you insert more letters for your name
then expected"?
I do not understand, why a char
to int
conversion should help in that case. Rather you should scan name
with the use of strlen()
of how many characters the string is contained of and make a if/else
-statement thereafter based on the return value of strlen()
.
Also as i already mentioned in my comment, but twice is better:
You have forgot that you need one element to store the \0
-terminator for the string, which is automatically inserted at the end of the string if you use scanf("%s",&name);
, so name
should be declared as char name[N + 1];
. If you make it like you have now, you will easily get into buffer overflow. Also if possible, scanf()
should have a width modifier to avoid exactly the same thing, even if the width is not fixed at compilation and generated at run-time. A trick to use a variable (not fixed) width modifier, as you need it if you want to incorporate one, is written down in one answer on that question:
Width Specifier for scanf() - Length of characters to consume is not fixed at compilation and only determined at run-time. How to make it variable?
Always remember: Make your program as safe as possible.