Few questions about C syntax

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

    In simple terms:

    1) since malloc returns a pointer of type void, you are casting that pointer to a pointer of type char so that the variable ch will later hold an array of characters (a string )

    2) the single quotation marks are mainly used because a switch statement in C always expects an INTEGER and, not a string. having a character surrounded by single quotations would return the integer representation of the character.

    3) This is a common problem when using scanf, basically it is caused by by the carriage return that is entered from the previous scanf. I would recommend that you always flush the input before using it.

    Here's an example:

    #include 
    
    int main (void)
    {
        char line[200];
        while(1)
        {
            printf("\nenter a string: ");
            fflush(stdout);         // safety flush since no newline in printf above
            scanf(" %[^\n]",line);  // note space character
            printf("you entered >%s<\n",line);
        }
        return 0;
    }
    

提交回复
热议问题