Unexpected behavior of printf() - c

I executed following code in ubuntu with gcc compiler.
As a=0, the second printf() prints some garbage value.
What kind of behavior is it by printf()?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a = 0;
printf("\nThe Value of %ns : %d\n", &a, a);
printf("\n%d\n", a);
printf("\n\n");
return 0;
}

If you read e.g. this printf reference you will see that the %n format specifier will:
returns the number of characters written so far by this call to the function.
So it will overwrite the contents of a with the number of characters it has written so far, which should be 14 if I count correctly.

The output of the first printf is 0
Because the second argument of printf passes a by the value and it gets printed afterwards.
The output of the second printf is 14
Because at this time the value of a was replaced by the number of characters that was printed before %n by the first printf

As a=0, the second printf() prints some garbage value.
You can't believe that statement until you verify it!
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a = 0;
printf("\nThe Value of %ns : %d\n", &a, a);
assert(a == 0);
printf("\n%d\n", a);
printf("\n\n");
}
Any time you want to say "I'm sure that (some invariant) is true at place x", use assert to state that fact and let it be checked at runtime.
Output:
output.s: ./example.c:8: main: Assertion `a == 0' failed.

Related

Input multiple integer values and print them in C

I'm new to C language. Here's the code I used to get input for a and b and print them. But I did not get the values I entered via the terminal can you explain why I got different values for a and b?
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
int a,b;
scanf("%d, %d", &a, &b);
printf("%d, %d", a, b);
return 0;
}
I entered 5 9 as inputs, but I got 5 and 16 as outputs.
You need to check the value of scanf() otherwise some or all the values you attempt to use are undefined. In your case the input you provided did not match the scanf() format string. I changed the format string to match the input you provided, removed headers that are not used and added a newline to your printf() statement:
#include <stdio.h>
int main(void) {
int a, b;
if(scanf("%d%d", &a, &b) != 2) {
printf("scanf failed\n");
return 1;
}
printf("%d, %d\n", a, b);
}
You don't have to use comma (,) to separate 2 inputs in scanf() function. This function automatically separates your inputs by number of occurrences of format specifiers i.e. %d in your case. However you have to separate variable addresses using comma.
Just use it like scanf("%d %d", &a, &b).

Finding sum of 2 variables from 1 statement in C

I recently started learning C and must create program that scanf two integer values from standard input separated by a space then printf the sum of these two integers. Must be able to accept negative values. I'm using repl.it to write code 1st then pasting in .c to compile.
Attempt:
#include <stdio.h>
int main(void) {
int j = 0;
printf("Enter 2 integers separated by space and press enter:\n");
while (scanf("%d", &j) == 1) {
printf("Here is the sum:"%d", j);
}
return 0;
}
Except this prints
Here is the sum: 1Here is the sum: 2
The output is wrong so what mistake did I make? Whats the correct method to get expected values?
(eg 1+2=3)
Your code is incorrect. It does not even compile due to "Here is the sum:"%d" ill formatted string. The program will repetitively scan an integer from standard input and print it as it was result of a sum.
Parsing two integers separated by a space can be easily done with scanf() function by using "%d %d" pattern. The function scanf() returns a number of successfully parsed arguments thus value of 2 is expected on correct input. Finally, add both number and print the result.
#include <stdio.h>
int main(void) {
int i, j;
if (scanf("%d %d", &i, &j) == 2) {
printf("Here is the sum: %d\n", i + j);
return 0;
}

Why this program does not print the desired output?

I just know about the %i format specifier from this link
Difference between format specifiers %i and %d in printf
and I tried to implement it with this program.
#include <stdio.h>
int main(){
long long a,b;
printf("Input: ");
scanf("%i %lld",&b,&a);
printf("Output: %i %lld",b,a);
}
%i worked properly but %lld stores a garbage value in variable a.
This is the output of this program.
Input : 033 033
Output : 27 141733920846
Process returned 0 (0x0) execution time : 4.443 s
Press any key to continue.
Can anyone explain, why I am getting the garbage value in variable a?
scanf %i takes an int *, but you're passing &b, which is a long long int *. This has undefined behavior.
You should be using %lli.
The same problem occurs in printf: Use %lli to print b, not %i.
You should also check scanf's return value to make sure two values were successfully read.
First of all, using %i for a long long int is undefined behavior, so use %lli instead.
The same issue persists in the printf statement, too.
Fixed code:
#include <stdio.h>
int main(){
long long a,b;
int retval;
printf("Input: \n");
retval = scanf("%lli %lld",&b,&a);
printf("Output: %lli %lld",b,a);
printf("\nRetval: %d",retval);
return 1;
}
Input:
033 033
Output:
Input: Output: 27 33 Retval: 2
Live Demo
Note: Always check the return value of scanf. It returns the number of scanned items, which you should test against your expectations.

Scanf in c seems to require double input?

This is probably a really basic question but has me stumped so here goes.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
float argument = 8.86;
printf("%f%\n", argument);
argument = 7.75;
printf("%f%\n", argument);
scanf("%f%\n", &argument);
printf("%f%\n", argument);
return 0;
}
I just wrote this code to help me figure out whats going on. Basically, the scanf seems to require me to put any number then press enter as expected, but then enter another number and press enter or just press enter (after which it will then print the value put the FIRST time time). Shouldn't the code just immediately print the entered number and finish?
Could anyone explain how or why this is happening, thanks!
You have an extra % in scanf() and printf() calls. scanf() attempts to intrepret it as additional conversion character. This results in undefined behaviour. Remove them.
If you want to print % sign, use %%.
E.g.:
printf("%f%%\n", argument);
First, you have an extra % in printf() and scanf() function;
Second, you should not have \n in scanf() function;
if have the \n, the console will ignore new line, space and all blank characters when you input.
Maybe like this:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
float argument = 8.86;
printf("%f\n", argument);
argument = 7.75;
printf("%f\n", argument);
scanf("%f", &argument);
printf("%f\n", argument);
return 0;
}
I am also a beginner in C language. We come together!
Try this:
#include <stdio.h>
int main()
{
char str1[20], str2[30];
printf("Enter String 1: ");
scanf("%s", &str1);
printf("Enter your String 2: ");
scanf("%s", &str2);
printf("String 1: %s\n", str1);
printf("String 2:%s", str2);
return(0);
}
**Only change in scan function **
from scan(%d\n)
to

Scanf continuous input in C

#include <stdio.h>
int main ()
{
double a=0;
char b=0;
scanf ("%d%c",&a,&b);
printf ("%d,%c", a, b);
return 0;
}
This is my code for a quick test program I wrote to play around with the scanf function in C. I am trying to have the user input something like 78X + 5 = 19 (then hit enter) and then parse that into variables a, b, and c where in this case a=78, b=5, c=19. In the sample code, when I type in 78X, c doesn't store a value to b and only prints "78, " and then terminates. Why won't it store a value to b?
If your input is 75x then below is the code which reads the value and stores it in a(75) and b(x) respectively
#include <stdio.h>
int main ()
{
int a=0;
char b=0;
scanf ("%d%c",&a,&b);
printf ("%d%c", a, b);
return 0;
}
The , in your format string is significant. The string %d,%c would match the input 78,x but it would not match 78x .
Also you need to use %f to scan and print a double. Using %d causes undefined behaviour (which may manifest itself as b seeming to not appear). Either change to %f, or change your double to an int.

Resources