Home > OS >  How does scanf store value?
How does scanf store value?

Time:06-30

I'm new to C. Given the following code,

int main(void)
{
 int a;
 scanf("%d",&a);
 scanf("\n"); // consume trailing newline
}

As I understand it, the first declaration statement tells the compiler to allocate memory for an integer type variable with an identifier 'a' initialized to 0(as 'a==0'). Scanf needs a valid memory address to store the user input(say 5) so &a being the memory address of 'a' is where the user input is stored as 'a==5'. Is this the case or 'a' is stored as a variable name for the memory address and the contents of the address are simply 5?

CodePudding user response:

Is this the case or 'a' is stored as a variable name for the memory address

&a is a pointer to the memory reserved for a. The name “a” is not involved.

... initialized to 0

Automatic objects are not initialized by default. Any object declared inside a function without static, extern, or _Thread_local has automatic storage duration.

The value of an uninitialized object is indeterminate, meaning it has no fixed value; it may behave as if it has a different value each time it is used. (If you explicitly initialize any part of an automatic object, such as one element of an array or one member of a structure, the entire object will be initialized, defaulting to zeros for numeric types and null pointers for pointer types.)

  • Related