Wednesday, July 17, 2013

What happens if we don't use address-of in scanf

In C, while using the scanf() function, we have to specify arguments with address-of(&) operator to take the values which we give into the variables. But what happens when we don't place the address of operator? Does it return a error or works well?

Check out the following program to understand it well.

  1. #include<stdio.h>
  2. main()
  3. {
  4. int a;
  5. printf("Enter a value");
  6. scanf("%d",a);
  7. printf("%d", a);
  8. return 0;
  9. }
The output of the above program is some garbage value as the value at the 'a' is not the value taken. It is some garbage value.

If you clearly understand, the problem here, you will find a solution. What happens when we use a scanf function is, it takes the address at which the value need to be stored. Here we are directly sending the variable instead of the address. So, the scanf() thinks that it is the address and places the taken value into the address which the variable specifies.

Actually, the variable contains some garbage value and the it is passed as address to the scanf() function. Hence when we print the value, it is showing some other value. To solve this issue, we can use the concept of pointers and solve this problem.

Checkout the following program,
  1. #include<stdio.h>
  2. main()
  3. {
  4. int a, *b;
  5. b=a;// Taking the value in a into b
  6. scanf("%d",a);// Value is stored at the address, which is the value a is having( some garbage)
  7. printf("%d", *b); //printing the value at the address which b is holding ( a's garbage value)
  8. return 0;
  9. }
This program may show some warnings. But works well. This is because we have given an explanation as in the form of comments. If you still don't understand feel free to contact me.