Few questions about C syntax

后端 未结 8 798
暖寄归人
暖寄归人 2021-01-24 02:58

I have a few questions about C syntax.

  1. ch = (char *) malloc( sizeof( char ) * strlen(src) ); What do the first brackets mean (char *) ?

8条回答
  •  不知归路
    2021-01-24 03:16

    1. (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.

    2. '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}.

    3. 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).

提交回复
热议问题