-1

私は 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;
}
4

2 に答える 2

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);
于 2013-10-07T18:39:31.890 に答える
0

ご覧のとおりx、この呼び出しではポインターではありません

show_bytes(x, length);  

関数定義に反するもの

void show_bytes(byte_pointer start, int length)  
                    ^
                    |
               Expects a pointer  

この声明では

x[locationFromRight] =  b;  

xポインターでも配列でもありません。

于 2013-10-07T18:39:50.743 に答える