2013-10-07 95 views
-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; 
} 
+0

为什么你使用指针而不是按位和? – user1937198

+0

对于bitewise操作符,我仍然很模糊。你知道任何可以描述我想要做什么的资源吗?我不知道该怎么谷歌来得到我需要的东西:) –

+0

维基百科如何:http://en.wikipedia.org/wiki/Bitwise_operations_in_C – user1937198

回答

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); 
+0

阅读有关大端与小端。如果没有意义,请稍后重读。 – ChuckCottrill

0

当我看到x不在此调用

show_bytes(x, length); 

这是对你的函数定义

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

在这份声明中

指针
x[locationFromRight] = b; 

x是neithr指针或数组。