我是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;
}
答案 0 :(得分:3)
您的功能定义
void show_bytes(byte_pointer start, int length)
将指针作为第一个参数
typedef unsigned char *byte_pointer;
但是在函数replace_byte()
unsigned replace_byte(unsigned x, int i, unsigned char b)
您将x
声明为unsigned
类型show_bytes()
show_bytes(x, length);
答案 1 :(得分:0)
我看到x
不是此调用中的指针
show_bytes(x, length);
哪个违反了您的功能定义
void show_bytes(byte_pointer start, int length)
^
|
Expects a pointer
在本声明中
x[locationFromRight] = b;
x
是neithr指针,也不是数组。