Adding two numbers to char variables read with scanf
I was teaching the C programming language to a friend and we came up with something that I couldn't explain. This is the code we wrote:
#include <stdio.h>
int main(void)
{
char num1;
char num2;
printf("%s", "Enter the first number: ");
scanf("%d", &num1);
printf("%s%d\n", "The number entered is:", num1);
printf("%s", "Enter the second number: ");
scanf("%d", &num2);
printf("%s%d\n", "The number entered is:", num2);
printf("%s%d\n", "The first number entered was:", num1); /* This was done for testing */
printf("%s%d\n", "The sum is:", num1+num2);
return 0;
}
The weird thing is that we tried to do 5 + 6 and we expected to get 11 but got 6 instead, I added a line to see what happens with the first number and after the second read it will be 0.
I know the variables should be int
(in fact the original code was like this and worked), but I understand that it char
is a small integer, so I thought it would be "safe" to use if we add small numbers.
The code has been tested and compiled on a Linux machine using cc
and on a Windows machine with cl
. The result was the same. On a Windows machine, the program gives an error after adding.
I would like to explain why this code does not work as I expected. Thanks in advance.
source to share
You cannot pass a pointer to another data type to scanf
. scanf
will write to memory if you gave it a pointer to what it was expecting (for example, int
for %d
), and will exhibit wonderful undefined behavior if you give it a pointer to a different data type.
Here it is most likely that scanf
overwrites, for example. 4 bytes in your stack when yours char
only takes 1 byte, so it scanf
will just happily write right above some other variable in your stack.
source to share
a char is a small integer, so I thought it would be "safe" to use it if we were adding small numbers.
Correct, char
is a small integral type and should be used in integer arithmetic (although it char
can be signed or unsigned, which can lead to unexpected results).
But the problem is that the pointer tochar
CANNOT be used in the place where the pointer toint
is expected . And this is the case for scanf("%d", &num1);
, the second parameter must be of type int *
.
source to share