简体   繁体   English

C-将字符串输入到int变量中?

[英]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 . 我将输入字符串存储在i的地址中。 When I try to print the variable i , I get some number. 当我尝试打印变量i ,我得到了一些数字。

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. 该程序将从用户读取的字符串写入变量i占用的内存中,并传递给它。 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. 实际上发生的是,在您的计算机上int的大小为4个char ,而字符“ hell”在转换为ASCII并解释为CPU字节顺序的数字时,实际上是数字1819043176。其余部分字符串中的字母,字母o和结尾的nul字符超出了i在您的计算机上存储的末尾。 So what scanf does is this: 那么scanf作用是:

  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. 您似乎是在低位字节序的计算机上运行此程序的,因此,当将字节68 65 6c 6c存储到int中时,它将被解释为数字0x6c6c6568或十进制1819043176

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. 如果int大小不同,或者机器使用了另一个字符集(例如EBCDIC而不是ASCII),或者CPU使用了大端字节序,或者如果程序在已对内存写入进行绑定检查的环境中运行,则可以会得到不同的结果或程序崩溃。 In short, undefined behavior. 简而言之,未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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