简体   繁体   English

C指针:当你取消引用一个char指针并尝试存储一个int时,它会存储整个int吗?

[英]C pointers: When you dereference a char pointer and try to store an int, will it store the whole int?

Let's say you have: 假设你有:

    void *p = // something;
    int size = 10;
    *((char *)p + 8) = size ^ 1;

I know this looks like really random logic, but I was wondering if it would still do as intended. 我知道这看起来像是随机的逻辑,但我想知道它是否仍然按预期进行。 I am trying to place the entirety of "size ^ 1" at the address pointed to by "p + 8" when p is casted to a char. 当p被转换为char时,我试图将“size ^ 1”的整体放在“p + 8”指向的地址处。 Basically what I am asking is, is it any different from: 基本上我要问的是,它有什么不同:

    *((int *)p + 2) = size ^ 1;

Also, what would happen if I had chosen to increment the pointers by 3, for example: 此外,如果我选择将指针增加3,会发生什么,例如:

    *((char *)p + 3) = size ^ 1;

or (I know this isn't equivalent to all the others, but want to see if this is right): 或(我知道这不等于所有其他人,但想看看这是否正确):

    *((int *)p + 3) = size ^ 1;

When you derefence a char * pointer, you are referring to a single char object. 当你对char *指针进行derefence时,你指的是一个char对象。 In this way, it is very similar to: 这样,它非常类似于:

char c;

c = size ^ 1;

That is, the resulting value (in this case, 11) is converted to type char and then stored at the location (char *)p + 8 (the 9th char object pointed to by p ). 也就是说,结果值(在这种情况下为11)转换为char类型,然后存储在位置(char *)p + 8p指向的第9个char对象)。

So yes, it is quite different from: 所以是的,它与以下内容完全不同:

*((int *)p + 2) = size ^ 1;

The latter line modifies an entire int object, of size sizeof(int) , and the object modified is the 3rd int object pointed to by p . 后一行修改整个int对象,其大小为sizeof(int) ,修改的对象是p指向的第3个int对象。

If we imagine that you have a little-endian system with sizeof(int) == 4 , then your four examples will modify the memory pointed to by p in the following ways: 如果我们想象你有一个sizeof(int) == 4的little-endian系统,那么你的四个例子将通过以下方式修改p指向的内存:

1. 1。

*((char *)p + 8) = size ^ 1;

| ?? | ?? | ?? | ?? | ?? | ?? | ?? | ?? | 11 | ?? | ?? | ?? | ?? | ?? | ?? | ?? |

2. 2。

*((int *)p + 2) = size ^ 1;

| ?? | ?? | ?? | ?? | ?? | ?? | ?? | ?? | 11 | 00 | 00 | 00 | ?? | ?? | ?? | ?? |

3. 3。

*((char *)p + 3) = size ^ 1;

| ?? | ?? | ?? | 11 | ?? | ?? | ?? | ?? | ?? | ?? | ?? | ?? | ?? | ?? | ?? | ?? |

4. 4。

*((int *)p + 3) = size ^ 1;

| ?? | ?? | ?? | ?? | ?? | ?? | ?? | ?? | ?? | ?? | ?? | ?? | 11 | 00 | 00 | 00 |

*((char *)p + 8) = size ^ 1 implicitly casts size ^ 1 to char , which jettisons all but the lowest-order byte; *((char *)p + 8) = size ^ 1隐式地将size ^ 1强制转换为char ,除了最低位字节之外的所有内容都被抛出; so no, it is not the same as *((int *)p + 2) = size ^ 1 . 所以不,它与*((int *)p + 2) = size ^ 1

*((char *)p + 8) = size ^ 1; is no different than: 没有什么不同于:

char something;
something = size ^ 1;

You can figure it out from there, but better just try it and find out! 你可以从那里弄清楚,但更好的只是尝试并找出答案!

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

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