[英]Can't understand the output
Code looks like this. 代码看起来像这样。
#include<stdio.h>
int main(){
int vals[2];
char *x;
int *v, *v2, *v3;
vals[0] = 0x00ABCDEF;
vals[1] = 0x12345678;
x = (char *) &vals[0];
v = (int *) (x + 1);
v2 = (int *) (x+2);
v3 = (int *) (x+3);
printf ("%x \n", *x); /*0x EF */
printf ("%x \n", *v); /*0x 7800ABCD */
printf ("%x \n", *v2); /*0x 567800AB */
printf ("%x \n", *v3); /*0x 34567800 */
}
The values in the comment is the output. 注释中的值是输出。 could you explain how x points to EF and also v , v2, v3.
您能否解释x如何指向EF以及v,v2和v3。 what is the explanation to that.
这是什么解释。 i know that one hex digit is four bits and one int can store 8 hex digits but can't understand how the x points to EF and not 00 which are the first two letters and why the last two letters and not the first two.
我知道一个十六进制数字是四个位,一个int可以存储8个十六进制数字,但无法理解x如何指向EF而不是00,它们是前两个字母,以及为什么后两个字母而不是前两个字母。
If your system has alignment requirements, then v = (int *) (x + 1);
如果您的系统有对齐要求,则
v = (int *) (x + 1);
(and the next two lines) cause undefined behaviour due to an alignment violation. (以及接下来的两行)由于对齐冲突而导致未定义的行为。
But even if they don't, *v
later on causes undefined behaviour by violating the strict aliasing rule. 但是即使不这样做,
*v
稍后也会通过违反严格的别名规则而导致未定义的行为。 The expression *v
has type int
, and it is not allowed to use this type of expression to access char
objects (or in fact any objects other than int
, unsigned int
or const-qualified versions of those). 表达式
*v
类型为int
,不允许使用这种类型的表达式来访问char
对象(或者实际上是除int
, unsigned int
或const限定版本之外的任何对象)。
Undefined behaviour means that anything may happen, including nonsense output or otherwise. 未定义的行为意味着任何事情都可能发生,包括无意义的输出或其他。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.