Reputation: 97
I thought that I understood C but i am having a hard time just writing a simple addition code for practice. When I run this code, int a is 0 every time. However, int b works fine. The idea here is that the input to the program is 8 + 9. Why does sscanf not recognize variable a?
#include <stdio.h>
#include <stdlib.h>
int plus(int a, int b){
return (a + b);
}
int main()
{
int a, b;
char input[100], op;
printf("...I am ZOLO...\n");
printf("...The most vercatile calculator known to man...\n");
printf("...Please enter your query:");
fgets(input, sizeof(input), stdin);
sscanf(input, "%d %s %d", &a, &op, &b);
printf("%d + %d = %d...", a, b, plus(a, b));
return 0;
}
Upvotes: 0
Views: 133
Reputation: 488183
Jonathon Reinhart has the correct answer. In this case, it's not just the undefined behavior problem, it's the fact that the compiler managed to allocate op
just before a
(in internal memory order) and your machine uses little-endian byte order so that the '\0'
character stored after op
wipes out the value that was previously stored to a
.
Upvotes: 1