2014-12-03 68 views
-2

我有一個鏈接列表,似乎工作得很好。我現在試圖從一個不同的方法訪問它,這是它有問題的地方。我有一個接收產品ID並在列表中搜索的功能。如果找到了,則返回整個節點。這是什麼樣子:C鏈表訪問問題

struct product* searchForProduct(int * id){ 

    struct product *pProductIterator = pFirstNode; 

    while(pProductIterator != NULL){ 

    int areTheyEqual; 

    if(pProductIterator->id == id){ 
     areTheyEqual = 0; 
    } 
    else{ 
     areTheyEqual = 1; 
    } 

    if(areTheyEqual == 0){ 
     printf("Item %d : costs %f", 
      pProductIterator->id, 
      pProductIterator->price); 

     return pProductIterator; 
    } 

    pProductBeforeProductToDelete = pProductIterator; 
    pProductIterator = pProductIterator->next; 
    } 

    printf("%d wasn't found\n\n", id); 

    return NULL; 
} 

上面的代碼工作正常,在這個意義上,它會搜索並打印出來,如果該項目已被發現或沒有。但是我正在努力的是讓返回的節點工作。我想打電話給這樣的事情:

int z = 5; 
itemprice = searchForProduct(z)->price; 

我想要做的就是找到項目z(ID 5),採取其price值,並將其保存到變量itemprice。然而,我得到的是這樣的:

error: dereferencing pointer to incomplete type 

warning: passing argument 1 of 'searchForProduct' makes pointer from 
integer without a cast 

我不知道這意味着什麼,所以任何想法將非常感激在這裏。

+0

功能'searchForProduct'應該採取'INT id',不'INT * id'。不僅是因爲編譯錯誤(你也可以通過投射解決),而且因爲你使用'「%d」'來打印它! – 2014-12-03 11:28:35

+0

爲什麼'id'' int *'的類型?我應該是'int'。 – ikh 2014-12-03 11:31:02

回答

1

試試這個:

//Actually declare the structure of the struct. This is why you get an incomplete type error. 
//I've added the minimum number of members mentioned in your code. 
struct product { 
    int id; 
    float price; 
}; 


struct product* searchForProduct(int id){ //Not int*. No need to pass a pointer id isn't a array or structure or modifiable. 

    struct product *pProductIterator = pFirstNode; 

    while(pProductIterator != NULL){ 

    int areTheyEqual; 

    if(pProductIterator->id == id){ 
     areTheyEqual = 1; //The universal convention (including C) is that 0 is false, everything else is true. 
    } 
    else{ 
     areTheyEqual = 0; //They are not equal. 
    } 

    if(areTheyEqual){//As stated C interprets 0 as 'false' and everything else 'true'. 
     printf("Item %d : costs %f", 
      pProductIterator->id, 
      pProductIterator->price); 

     return pProductIterator; 
    } 

    //pProductBeforeProductToDelete = pProductIterator; //Code removed. Doing nothing... 
    pProductIterator = pProductIterator->next; 
    } 

    printf("%d wasn't found\n\n", id); 

    return NULL; 
} 

還做這樣的事情:

int z = 5; 
struct product *item=searchForProduct(z); 
if(item!=NULL){ 
    itemprice=item->price; 
}else{ 
    //Do something about not finding the product here! 
    itemprice=0.0;//Might be a good start.... 
} 

你的版本

searchForProduct(z)->price; 

取消引用一個NULL指針當產品unfound。它有完全未定義的行爲,儘管可能會崩潰整個程序。這是每個C程序員生活的禍根,你應該養成習慣,儘快處理它。

1

在你的函數原型,

struct product* searchForProduct(int * id); 

ID不應該被聲明爲指針,其定義應是

struct product* searchForProduct(int id);