C指针管理(地址,解除引用,重新分配)

时间:2017-09-07 20:54:58

标签: c pointers byte bits

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

有人可以帮我修复这段代码,以便px指向地址,然后我可以增加pc(与px相同,但只是作为char以避免增加太多字节)然后替换mem中的内容用其他东西定位电脑?

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;
}

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

当我想要获得这样的值时:

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

2 个答案:

答案 0 :(得分:1)

这对我很有用:

#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);
}

答案 1 :(得分:0)

此代码演示了如何更改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