How does the scanf function work in C? -


why require ampersand (&) in scanf function. output or type of error (compile or runtime) in following c code?

#include <stdio.h>  void main() {     int a;     printf("enter integer:");     scanf("%d", a); } 

the & in c operator returns address of operand. think of way, if give scanf variable a without &, passed by-value, means scanf not able set value see. passing by-reference (using & passes pointer a) allows scanf set calling functions see change too.

regarding specific error, can't tell. behavior undefined. sometimes, might silently continue run, without knowing scanf changed value somewhere in program. cause program crash immediately, in case:

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

compiling shows this:

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

and executing shows segmentation fault:

$ ./test  enter integer: 2 segmentation fault 

Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -