2014-01-06 117 views
0

赦免任何無知 - I是比較新的C.我有以下功能:指針在C功能參數爲NULL

int get_fingerprint_device(struct fp_dev *device) { 
    struct fp_dscv_dev **devices; 
    int rtn; 

    if (!(devices = fp_discover_devs())) { 
     rtn = -1; 
    } 
    else { 
     if (!(device = fp_dev_open(*devices))) { 
      rtn = -2; 
     } 
     else { 
      if (device) { 
       printf("Device OK\n"); 
      } 

      rtn = 1; 
     } 

     fp_dscv_devs_free(devices); 
    } 

    return rtn; 
} 

我有一個main()如下:

int main(void) 
{ 
    // Vars 
    struct fp_dev *device; 
    struct fp_print_data **print_data; 
    struct fp_img **img; 
    int err; 

    // Init libfprint 
    fp_init(); 

    // Get the first fingerprint device 
    if ((err = get_fingerprint_device(device)) < 0) { // Errorz 
     if (err == -1) { 
      error("No devices found"); 
     } 
     else if (err == -2) { 
      error("Couldn't open the device"); 
     } 

     return 1; 
    } 

    if (device == NULL) { 
     printf("No\n"); 
     return 1; 
    } 
    else { 
     printf("Yes\n"); 
     return 0; 
    } 

    fp_enroll_finger_img(device, print_data, img); 

    // Deinit libfprint 
    fp_exit(); 

    return 0; 
} 

運行結果是它首先打印「設備確定」,然後打印「否」。

爲什麼設備是get_fingerprint_device()中的有效指針,而不是返回main()時的有效指針?我的理解是,我應該在這裏使用一個雙指針,這樣內部指針的值可以改變並傳播回main()...但是實現到目前爲止還是沒有。

回答

1

這是因爲device是按值傳遞到get_fingerprint_device。換句話說,該函數獲取自己的device指針副本。然後它爲它分配了一些內容,但該更改在該函數外部是不可見的,所以一旦它返回,調用者(在這種情況下爲main)看不到任何更改。如果你想這個工作,你必須將指針的指針傳遞給get_fingerprint_device函數(即struct fp_dev **device)。

+0

感謝您的答案。因此,我的實現是:https://gist.github.com/phil-lavin/d9c7e8f2ce5f6e3cf3e6但是它會在分配fp_dev_open()的行上導致段錯誤。任何提示? –

+0

這可能與fp_dev_open(* devices)segfaults無關。我會調查。 –

+0

現在工作,謝謝:) –

0

你對C中傳遞指針有點困惑 - 目前你只是傳遞「狂放」(未分配的)指針。你應該改變:

struct fp_dev *device; 

到:

struct fp_dev device; 

和變化:

if ((err = get_fingerprint_device(device)) < 0) 

到:

if ((err = get_fingerprint_device(&device)) < 0) 
+0

第一次更改(結構不是指針)在GCC中產生了這個。錯誤:設備的存儲大小在GCC中是未知的 –

+0

您可能不會#包含必需的標題。或者它可能是一個不透明的指針。如果沒有看到所有相關的標題等,很難調試您的代碼。 –