2014-12-03 74 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);