0

I'm learning C language by myself.

I wrote the following code and executed it.

Unexpectedly the "first" variable was 0, though I inputted 4.

Could you explain me why this happens and how to fix this?

Code:

#include <stdio.h>
#include <stdint.h>

int main(void) {
        int8_t first;
        printf("Fist parameter:");
        scanf("%d", &first);

        int8_t second;
        printf("Second parameter:");
        scanf("%d", &second);

        printf("%d * %d == %d\n", first, second, first * second);
        return 0;
}

Expected:

Fist parameter:4
Second parameter:5
4 * 5 == 20

Actual:

Fist parameter:4
Second parameter:5
0 * 5 == 0
neko-cat
  • 103
  • 1
  • 5
  • Turn on warnings for your compiler and pay attention to them. – Chris Dodd Jun 02 '17 at 02:35
  • Actually, that's not a duplicate. It's not a question of "what format specifier to use for int8", it's a much more interesting "why does it work this way" question. – iehrlich Jun 02 '17 at 02:42

2 Answers2

0

Change int8_t to int. Then this could work for you.

Yunbin Liu
  • 1,484
  • 2
  • 11
  • 20
0

You're using the %d format with scanf. %d assumes that the pointer it's used with points to an int, which is generally a 32-bit value (although it can be different sizes on different architectures). An int8_t is a one-byte value. Now, many computers these days are based on the Intel x86 family of processors, which is a "small-endian" architecture, meaning that the low-order part of a value stored from a register into memory goes into the low-order address of the block of memory (generally 4 bytes) where it's stored. Thus, when your program stored the value of 5 into second it was really storing four bytes of data, which in hex would be 0x00000005. The 05 was stored into second, the low-order 00 was stored into first and the next two bytes of zeroes overlaid whatever was "next to" first in memory - so, congratulations, your program has a memory overwrite bug! It may not have been fatal, but it's there. :-)

As an experiment, try changing the types of first and second to int. I'll bet it then works as expected.

Best of luck.