C 指针管理(地址、取消引用、重新分配)

C Pointer Mangement (Address, Dereferencing, Reassigning)

我正在尝试编写一个函数来访问一个字节并将其更改为另一个字节。我在管理指针时遇到问题。

谁能帮我修改这段代码,让 px 指向地址,然后我可以递增 pc(这与 px 相同,但就像 char 一样,以避免递增太多字节),然后替换原来的内容在 mem 位置 pc 和其他东西?

unsigned replace_byte(unsigned x, int i, unsigned char b){
    unsigned int* px = &x; //Takes initial address of first byte.
    unsigned char* pc= (unsigned char*)px; //Recast it too char 
    //pointer to avoid incrementing by too many bytes
    if (i==0) {
       *pc= b; //if i is 0 then replace the byte at mem location pc 
    //with b
    }
    if (i==1) { //if i is 1 or more then inc by that much and replace
        pc = pc+1;
        *pc= b;
    }
    if (i==2) {
       pc=pc+2;
       *pc= b;
    }
    if (i==3) {
        pc=pc+3;
       *pc= b;
    }
    return x;
}

我得到的 return 值如下: 305419947 305441656 313218680 2872333944

当我想获得这样的值时:

replace_byte(0x12345678, 0xAB, 2) --> 0x12AB5678 replace_byte(0x12345678, 0xab, 0) --> 0x123456AB

这对我来说非常有效:

#include <stdio.h>

unsigned replace_byte(unsigned x, int i, unsigned char b){
    unsigned int px = x;
    unsigned char* pc= (unsigned char*) &px;
    if (i > 3) return px;
    *(pc + i) = b;
    return px;
}

int main()
{
    int a = 0x12345678;
    a = replace_byte(a, 2, 0x7F); // any hexadecimal character in parameter 3
    printf("%x", a);
}

此代码演示如何更改 int 类型的特定字节。

#include <stdio.h>

int main() {
    unsigned int i = 0xffffffff;

    //// make two pointers to the one memory address
    // x - pointer to int. The address will be shifting by 4 bytes, when this
    // pointer will be shifting by 1.
    int *x = &i; 

    // y - pointer to char. The address will be shifting by 1 byte, when this
    // pointer will be shifting by 1.
    char *y = (char *) x;

    //addresses the same here.
    printf("x address = %p\n", x); 
    printf("y address = %p\n", y); 
    puts("");
    //both pointers are shifting by 1, but addresses are different now.
    printf("x + 1 = %p\n", x+1);
    printf("y + 1 = %p\n", y+1);
    puts("");
    //changing the 'i' original value by one byte in turns, one after another.
    printf("i - original:                %x\n", i); 

    *y = 16; 
    printf("i - the first byte changed:  %x\n", i); 

    *(y+1) = 16; 
    printf("i - the second byte changed: %x\n", i); 

    *(y+2) = 16; 
    printf("i - the third byte changed:  %x\n", i); 

    *(y+3) = 16; 
    printf("i - the forth byte changed:  %x\n", i); 

    return 0;
}

输出:

x address = 0x7fffe59e9794
y address = 0x7fffe59e9794

x + 1 = 0x7fffe59e9798
y + 1 = 0x7fffe59e9795

i - original:                ffffffff
i - the first byte changed:  ffffff10
i - the second byte changed: ffff1010
i - the third byte changed:  ff101010
i - the forth byte changed:  10101010