Few questions about C syntax

后端 未结 8 792
暖寄归人
暖寄归人 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:37
    ch = (char *) malloc( sizeof( char ) * strlen(src) );
    

    The (char*) is a cast. It says to treat the return value of malloc as a pointer to char. However, this is not necessary since void*, the return type of malloc is assignment compatible with all pointer variables in C.

    What's more the sizeof(char) is spurious since sizeof(char) == 1 by definition. Finally this allocation almost certainly allocates one element too few. There needs to be space for the zero terminator.

    So, it should probably be written:

    ch = malloc(strlen(src)+1);
    

    As for '1', this is a char literal. It has type int.

    This is not too be confused with "1" which is a string literal, of type char*, a pointer to a block of memory containing two chars, '1' followed by \0.


    As for question 3, it's not clear to me what you mean and in any case I will invoke the one question at a time rule to justify not addressing it! Others have answered that for you.

    0 讨论(0)
  • 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 <stdlib.h>.

    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? .

    0 讨论(0)
提交回复
热议问题