指针和结构

指针和结构

问题描述:

鉴于定义如下的结构和结构本书的数组LIB指针和结构

struct Book{ 
    char title[100]; 
    char author[100]; 
    int price; 
    struct Book *nextedition; 
}; 


struct Book lib[1000]; 

我打算写一个函数由给定笔者计算的书籍总价包括所有未来版本的书籍,即使未来版本的作者不是指定的作者。

title author price nextedition 
---------------------------------- 
0 Book1 Author1 25  &lib[2] 
1 Book2 Author2 20  NULL 
2 Book3 Author3 30  &lib[3] 
3 Book4 Author1 35  NULL 

对于上面的例子,这本书在LIB [2]是,在LIB下一版[0],这本书在LIB [4]是,在LIB下一版[2] 。因此,给定作者“作者1”,该函数应该返回90(= 25 + 30 + 35),并给予作者“作者3”,该函数应返回65(= 30 + 35)。

所以这是我的代码:

int firstEdition(char author[100]){ 
    int i, pos=-1; 
    for(i=0;i<numbooks;i++) 
    if(strcmp(lib[i].author,author)==0){ 
     pos=i; 
     if(pos>=0) return pos; 
    } 
    return -1; 
} 

int totalPrice(char author[100]){ 
    int price=0; 
    int i=firstEdition(author); 
    if (i<0) 
     return 0; 
    else {  
     while (lib[i].nextedition != NULL){ 
      price+=lib[i].price; 
      lib[i]=*(lib[i].nextedition); 
     } 
    return price;} 
} 

我试着运行上面的示例和作者=“作者1”的代码,并一直得到错误的输出。该函数总是返回55而不是90,我似乎无法弄清楚原因。任何帮助表示赞赏,谢谢!

totalPrice的实施在退出其while循环之前,先考虑列表中最后一本书的价格。它也改变了lib的一些成员,这显然不理想。

以下(未经测试)的代码应该给你正确的price不改变lib

int totalPrice(char author[100]){ 
    int price=0; 
    int i=firstEdition(author); 
    struct Book *book; 
    if (i<0) 
     return 0; 
    book = &lib[i]; 
    while (book != NULL) { 
     price+=book->price; 
     book = book->nextedition; 
    } 
    return price; 
} 
+0

哦,我看看,谢谢你的状态!你能告诉我如何在我的代码中更改lib的成员吗? – drawar 2013-05-07 16:50:58

+0

不客气。假设'lib'是一个全局变量,'lib [i] = *(lib [i] .nextedition)'行似乎改变了它。 – simonc 2013-05-07 16:52:09

+0

啊,明白了,谢谢你为我清理! – drawar 2013-05-07 16:56:10