I have a few questions about C syntax.
ch = (char *) malloc( sizeof( char ) * strlen(src) );
What do the first brackets mean (char *) ?
(char *)
is a cast; it means "treat the following value as a pointer to char
". In this particular case it's redundant and considered bad practice.
'1' is a character constant; somewhat non-intuitively, it has type int
(this is different from C++, where character constants are type char
). "1" would be a string constant, which is actually an array expression of type char [2]
and has the contents {'1', 0}
.
This is because a newline has been left in the input stream from the previous input operation. Suppose you type "foo" and hit Return; the input stream will then contain the characters 'f', 'o', 'o', '\n'. The first scanf
call reads and assigns "foo" to str
, leaving the trailing '\n' in the input stream. That stray newline is being picked up by the next scanf
call because the %c
conversion specifier doesn't skip whitespace (unlike just about every other conversion specifier).