简体   繁体   中英

C - Inputting string into an int variable?

In the following code,

#include <stdio.h>
int main()
{
    int i = 5;
    scanf("%s", &i);
    printf("%d\n", i);
    return 0;
}

I take the input string that is stored at the address of i . When I try to print the variable i , I get some number.

Input example:

hello

Output:

1819043176

What number is this and what exactly is happening?

This program writes the string that it reads from the user into the memory occupied by the variable i and past it. As this is undefined behavior, anything could happen.

What is actually happening is that on your machine int is the size of 4 char s, and the characters "hell", when converted into ASCII and interpreted as a number in the CPUs byte order, turns out to be the number 1819043176. The rest of the string, the letter o and the terminating nul character, are past the end of where i is stored on your machine. So what scanf does is this:

  h  e  l  l  o \0
|68 65 6c 6c|6f 00 ...
|          i|memory past i

You seem to be running this on a little-endian machine, so that when the bytes 68 65 6c 6c are stored into an int it's interpreted as the number 0x6c6c6568 , or 1819043176 in decimal.

If int was different size, or if the machine used another character set (like EBCDIC instead of ASCII), or if the CPU used big-endian byte order, or if the program runs in an environment where memory writes are bound-checked, you would get different results or a program crash. In short, undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM