Few questions about C syntax

后端 未结 8 911
暖寄归人
暖寄归人 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:38

    In:

    char *ch = (char *) malloc( sizeof( char ) * strlen(src) );
    

    The first (char *) casts the return value to a char *. In C, this is completely unnecessary, and can mask failure to #include .

    In addition, sizeof(char) is always 1, so is never needed.

    The character literal '1' has type int in C.

    Most likely getch returns an int. The string literal "1" consists of two characters. The digit 1 and the end of string marker NUL character. If you had used case "1": the return value of getch would be compared to the value of the pointer to "1" (after an implicit conversion to int).

    As for scanf, the input buffer might contain input that hasn't been processed by your program.

    See also Why does everyone say not to use scanf? What should I use instead? .

提交回复
热议问题