我是 C 的新手,我正在尝试编写一个函数来替换 unsigned int 中的特定字节。指针仍然让我有些模糊——有人愿意向我解释我在 replace_byte() 中的这些指针在概念上的错误是什么吗?提前致谢 :)
#include <stdio.h>
typedef unsigned char *byte_pointer;
void show_bytes(byte_pointer start, int length) {
int i;
for (i=0; i < length; i++) {
printf(" %.2x", start[i]);
}
printf("\n");
}
unsigned replace_byte(unsigned x, int i, unsigned char b) {
int length = sizeof(unsigned);
printf("X: ");
show_bytes(x, length);
printf("Replace byte position from left: %u\n", i);
printf("Replace with: %u\n", b);
printf("Combined: ");
int locationFromRight = (length - i - 1);
x[locationFromRight] = b;
show_bytes( (byte_pointer)&x, length);
}
int main(void) {
unsigned a = 0x12345678;
int loc = 2;
unsigned char replaceWith = 0xAB;
replace_byte(a, loc, replaceWith);
return 0;
}