使用C终场前char数组 [英] using C Pointer with char array

查看:165
本文介绍了使用C终场前char数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int i=512;
char *c = (char *)&i;
c[0] =1;
printf("%d",i);

这显示513,它增加了1到我。

this displays "513", it adds 1 to i.

int i=512;
char *c = (char *)&i;
c[1] =1;
printf("%d",i);

而这将显示256除以2吧。
可有人请解释一下为什么?非常感谢

whereas this displays 256. Divides it by 2. Can someone please explain why? thanks a lot

推荐答案

在二进制pssed 32位的数字512的前$ P $,仅仅是:

Binary

The 32-bit number 512 expressed in binary, is just:

00000000000000000000001000000000

,因为2至9的功率是512。以往,你读从右至左的位

because 2 to the power of 9 is 512. Conventionally, you read the bits from right-to-left.

下面是一些其他的十进制数的二进制文件:

Here are some other decimal numbers in binary:

0001 = 1
0010 = 2
0011 = 3
0100 = 4

的演员:Reinter preting的诠释为字节数组

当你这样做:

int i = 512;
char *c = (char *)&i;

你是间preting 4个字节的整数字符(8位字节)的阵列,因为你可能知道。如果不是,这里是发生了什么:

you are interpreting the 4-byte integer as an array of characters (8-bit bytes), as you probably know. If not, here's what's going on:

&i

取变量的地址 I

(char *)&i

reinter $ P $点它(或蒙上的话)的指针char类型。这意味着,现在可以象阵列使用。既然你知道了 INT 你的机器上至少有32位,可以通过访问其字节 C [0],C [1],C [2],C [3]

reinterprets it (or casts it) to a pointer to char type. This means it can now be used like an array. Since you know an int is at least 32-bit on your machine, can access its bytes using c[0], c[1], c[2], c[3].

根据系统的字节序时,数的字节可能被布置:第一最显著字节(大端),或至少显著字节第一(小端)。的 86 的处理器是小端。这基本上意味着数512被布置为在上面的例子中,即:

Depending on the endianness of the system, the bytes of the number might be laid out: most significant byte first (big endian), or least significant byte first (little endian). x86 processors are little endian. This basically means the number 512 is laid out as in the example above, i.e.:

00000000 00000000 00000010 00000000
    c[3]     c[2]     c[1]     c[0]

我已经分组位成对应于它们在内存布局方式不同的8位数据块(字节)。请注意,你也看过他们从右到左在这里,所以我们可以保持与约定二进制数字系统。

I've grouped the bits into separate 8-bit chunks (bytes) corresponding to the way they are laid out in memory. Note, you also read them right-to-left here, so we can keep with conventions for the binary number system.

现在设置 C [0] = 1 有这样的效果:

Now setting c[0] = 1 has this effect:

00000000 00000000 00000010 00000001
    c[3]     c[2]     c[1]     c[0]

这是 2 ^ 9 + 2 ^ 0 == 513 十进制。

设置 C [1] = 1 有这样的效果:

00000000 00000000 00000001 00000000
    c[3]     c[2]     c[1]     c[0]

这是 2 ^ 8 = = 256 十进制,因为你的覆盖第二个字节00000010 00000001

which is 2^8 == 256 in decimal, because you've overwritten the second byte 00000010 with 00000001

做一个的大端的系统说明,的字节的将被存储在逆序到的小尾数的系统。这意味着你会得到完全不同的结果来的人你有,如果你运行它在这些机器中的一个。

Do note on a big endian system, the bytes would be stored in reverse order to a little endian system. This would mean you'd get totally different results to ones you got if you ran it on one of those machines.

这篇关于使用C终场前char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆