So what actually this condition does?
this condition basically tests whether the char
pointer (aka a string
) s
points to nothing (i.e., address 0x0 in the computer's memory) which is the address of a special location in memory that we can't read from/write to it.
You'll know more about NULL, strings and pointers as you reach week 4. For now, take for granted that when s
is equal to NULL
, this means that no string exists at all.
how the user can input a NULL string?
well, the user doesn't actually inputs NULL
. Rather, as the professor said, she doesn't co-operate somehow. For example, since we have a limited amount of memory, if the user inputs a string that's too long to fit in the available memory we have, GetString()
will return NULL
and the string is never stored.
Another example would be if the user inputted a special value known as the end-of-file (aka EOF
). The end-of-file is a special value that indicates that there's no more data to read and I guess this is what the professor was referring to by "did not provide a string". In most Linux systems, this value is entered by pressing Ctrl + D from your keyboard.
When you don't input anything and press enter, the string that's stored is actually an empty string (i.e., ""
).
I tried to input numbers and special characters instead of string but
it also continued as if I had entered a valid string.
The numbers and special characters you inputted are interpreted as a whole string. Recall that a string is an array of chars where a char could be an uppercase letter, a lowercase letter, a digit or a special character. Recall also that the number 123 is NOT the same as the string "123" because the string "123" is actually an array of the digit chars '1', '2' and '3' where the number 123 is the integral value one hundred and twenty three.
How can I make sure that the user did input a valid string, not
numbers, not special characters and not an empty string?
If you wanna ensure that a string contains only alphabetical characters, you'll probably need to iterate over the characters of this string checking whether any of them is a non-alphabetical char. If so, you may take an appropriate action.
Functions declared in ctype.h (e.g., isalpha()
) may prove useful for this process.
Hope that helps!