2013-10-07 69 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給你變量的地址。