C 指针错误:从整数生成指针而不使用强制转换

C 指针错误:从整数生成指针而不使用强制转换,c,C,我是C语言的新手,我正在尝试编写一个函数来替换无符号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

我是C语言的新手,我正在尝试编写一个函数来替换无符号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;
}

你的函数定义

void show_bytes(byte_pointer start, int length)
将指针作为第一个参数

typedef unsigned char *byte_pointer;
但是,在函数中,替换_字节

传递声明为类型unsigned的x以显示_字节

正如我看到的,x在这个调用中不是指针

show_bytes(x, length);  
这违反了你的函数定义

void show_bytes(byte_pointer start, int length)  
                    ^
                    |
               Expects a pointer  
在这份声明中

x[locationFromRight] =  b;  

x既不是指针也不是数组。

为什么要使用指针而不是按位和?我对按位运算符也不太清楚。你知道有什么资源可以描述我正在尝试做什么吗?我不知道用谷歌搜索什么才能得到我所需要的:维基百科怎么样:阅读关于大端和小端的文章。如果没有意义,请稍后重新阅读。
void show_bytes(byte_pointer start, int length)  
                    ^
                    |
               Expects a pointer  
x[locationFromRight] =  b;