How does the scanf function work in C?

前端 未结 7 1679
孤独总比滥情好
孤独总比滥情好 2020-12-06 13:48

Why do you require ampersand (&) in the scanf function. What will the output or type of error (compile or runtime) be in the following C code?



        
7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-06 14:07

    The & in C is an operator that returns the address of the operand. Think of it this way, if you would simply give scanf the variable a without the &, it will be passed to it by-value, which means scanf will not be able to set its value for you to see. Passing it by-reference (using & actually passes a pointer to a) allows scanf to set it so that the calling functions will see the change too.

    Regarding the specific error, you can't really tell. The behavior is undefined. Sometimes, it might silently continue to run, without you knowing scanf changed some value somewhere in your program. Sometimes it will cause the program to crash immediately, like in this case:

    #include 
    int main()
    {
        int a;
        printf("enter integer: ");
        scanf("%d",a);
        printf("entered integer: %d\n", a);
        return 0;
    }
    

    Compiling it shows this:

    $ gcc -o test test.c
    test.c: In function ‘main’:
    test.c:6: warning: format ‘%d’ expects type ‘int *’, but argument 2 has type ‘int’
    

    And executing shows a segmentation fault:

    $ ./test 
    enter integer: 2
    Segmentation fault
    

提交回复
热议问题