简体   繁体   English

有人可以解释一下这个 C 程序的输出吗?

[英]Can someone please explain the output of this C program?

Here is the code:这是代码:

int a=256;
char *x= (char *)&a;
*x++ = 1;
*x =x[0]++;
printf("a=%d\n", a);

The output is:输出是:

a=257

int a=256;诠释a = 256;

Initialized integer variable with value 256. On little-endian machine memory layout is:初始化整数变量,值为 256。在 little-endian 机器上,内存布局为:

00 01 00 00 ...

char *x= (char *)&a;字符 *x= (字符 *)&a;

x is pointer to least significant byte of a (on little endian machine). x是指向 a 的最低有效字节a指针(在小端机器上)。

00 01 00 00 ...
 ^ -- x points here

*x++ = 1; *x++ = 1;

Set byte where x points to 1, then move x to next byte.x指向的字节设置为 1,然后将x移动到下一个字节。 Memory is:内存是:

01 01 00 00 ...
    ^-- x points here

*x =x[0]++; *x =x[0]++;

Unspecified behaviour, *x and x[0] are equal ( x[0] is *(x+0) ) .未指定的行为, *xx[0]是相等的( x[0]*(x+0) )。 Post-increment is ignored in your implementation.在您的实现中忽略后增量。

UPD: actually it is not ignored but overwritten by assignment. UPD:实际上它并没有被忽略,而是被赋值覆盖。 x[0]++ increases second byte: x[0]++增加第二个字节:

01 02 00 00
    ^ -- x

and then value taken before increment ( 01 ) placed to the same place by *x=然后在增量( 01 )之前取的值由*x=放置到同一位置

01 01 00 00

I'm going to take the posted code one line at a time.我将一次一行地使用发布的代码。

int a=256;

I presume this is straightforward enough.我认为这很简单。

char *x= (char *)&a;

This sets a char pointer to point to just one byte of the multi-byte int value.这将char指针设置为仅指向多字节int值的一个字节。 This is a low-level, machine-dependent, and not necessarily meaningful operation.这是一个低级的、依赖于机器的、不一定有意义的操作。 (Also x is a poor, unidiomatic name for a pointer variable.) (另外, x是一个糟糕的、单一的指针变量名称。)

*x++ = 1;

This both sets the byte pointed to by x , and increments x to point to the next byte.这既设置了x指向的字节,又增加了x以指向下一个字节。 In general that's a sensible operation — for example, it's how we often fill characters into a text buffer one at a time.一般来说,这是一个明智的操作——例如,我们经常一次将字符填充到文本缓冲区中。 In this context, though, it's borderline meaningless, because it's rare to move along the bytes of an int variable one at a time, setting or altering them.但是,在这种情况下,它是没有意义的,因为很少会一次移动一个int变量的字节,设置或更改它们。

*x =x[0]++;

And this line is completely meaningless.而这条线完全没有意义。 I'm not going to try to explain what it does, because I literally can't.我不会试图解释它的作用,因为我确实不能。

printf("a=%d\n", a);

Obviously this prints the value of a , although after what poor a has been through, it's hard to say what kind of bloody mess might be left of its bits and bytes.显然,这会打印a的值,尽管在经历了糟糕a之后,很难说它的位和字节会留下什么样的血腥混乱。

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

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