Few questions about C syntax

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

    Others have already answered yor First two Questions correctly, So I will answer your third Q:

    When you enter a character and hit the ENTER key, two characters are placed in the input buffer, the character and the newline character.

    You need to account for both of these. So First scanf consumes the newline and another reads the character.

    Step by Step Code Analysis:

    printf("enter string \n");   
    scanf("%s",&str);
    

    With above two statements, You see Enter the string and program waits for your input. Let us assume you enter the character C and pressed Enter once. When you perform this action, the input buffer receives two characters:

    1. The character C that you entered &
    2. The newline character \n

    The scanf statement reads just one character(C) from the input buffer.Thus, the newline character remains unread in the Inuput buffer.

    printf("enter char \n");  
    scanf("%c",&ch);  //does not scan my char
    

    With above two statements, enter char gets displayed but the scanf just skips(not wait for any uer input), this is because the unread newline character in the Input buffer is read by this scanf.

    So to appropriately receive the next input character you need an additional scanf.

    scanf("%c",&ch);  //with this second line do scan my char
    

提交回复
热议问题