2013-10-07 70 views
0

我正在做我在C中的第一个家庭作业任务,我正在尝试抓住指针。理论上它们是有意义的,但在执行中我有点模糊。我有这个代码,它应该是一个整数x,找到它的最低有效字节,并将Y替换为同一位置的该字节。 GCC返回与:初学者的指针(有代码)

“2.59.c:34:2:警告:15:6传递 'replace_with_lowest_byte_in_x' 的参数1时将整数指针,未作铸造

2.59.c [默认启用]:注意:期望'byte_pointer'但参数类型为'int'“

而且参数2也一样。有人会向我解释这里发生了什么?

#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"); 
} 

void replace_with_lowest_byte_in_x(byte_pointer x, byte_pointer y) { 
    int length = sizeof(int); 
    show_bytes(x, length); 
    show_bytes(y, length); 
    int i; 
    int lowest; 
    lowest = x[0]; 
    for (i=0; i < length; i++) { 
     if (x[i] < x[lowest]) { 
      lowest = i; 
     } 
    } 
    y[lowest] = x[lowest]; 
    show_bytes(y, length); 
} 

int main(void) { 


    replace_with_lowest_byte_in_x(12345,54321); 

    return 0; 
} 

回答

3

该函数需要两个指针,但你传递的是整数(-constant)s。你可能想要的是把数以自己的变量,并通过这些的地址功能:(在main):

int a = 12345, b = 54321; 

replace_with_lowest_byte_in_x(&a, &b); 

注意,你仍然传递不相容的指针。

+0

嘿 - 感谢您的帮助!我对C和指针非常陌生。修正了与常数有关的问题;然而,我将如何去访问/更改中的值? –

2

编译器是正确的,你的replace_with_lowest_byte_in_x()需要两个unsigned char *,但你传递两个int s到它。是的,int可以被视为内存地址,但它很危险,所以有警告。 &variable给你变量的地址。