0

我有以下代码:

Price *ptr=NULL;

Price *ptr1 = ptr;

ptr_file =fopen(pvalue,"r");
if (!ptr_file)
    exit(1);

while ((c=fgetc(ptr_file))!=EOF)
{       
    if(c==',' && flag==2)
    {
        temp_price[i] = '\0';
        i = 0;
        flag = 0;
        ptr->Price = atoi(temp_price);
        ptr->sold_cpy=0;
    }

    if(flag == 2)
        temp_price[i++]=c;  

    if(c==',' && flag == 1)
    {
       ptr->BookId[i++]='\0';
       i=0;
       flag=2;
    }
    if(!fflag)
    {
        ptr = (Price*) malloc (sizeof(Price));
        if (ptr==NULL) 
           exit (1);  
        flag=1;
        fflag=1;
    }

    if(flag == 1)
        ptr->BookId[i++] = c;

    if(c=='\n')
    {
       ptr = ptr->Next_Price;

       ptr = (Price*) malloc (sizeof(Price));
       if (ptr==NULL) 
           exit (1);    
        flag =1;               
    }   
}
ptr->Next_Price = NULL;
fclose(ptr_file);

for(ptr = ptr1;ptr!=NULL;ptr=ptr->Next_Price)   
    printf("%s %d %d\n",ptr->BookId,ptr->Price,ptr->sold_cpy);

问题是这些值被正确分配给 ptr 而不是 ptr1。我已经用 ptr1 指出了节点的开头:

Price *ptr1 = ptr;

这是结构定义:

typedef struct Price_ Price;
struct Price_{
char   BookId[20];
int    Price;
int    sold_cpy;
Price * Next_Price;
};

我完全厌倦了出了什么问题……有什么想法吗?

4

1 回答 1

0

你还没有创建链表,代码中有很多问题:

就拿这个:

您在此处检索下一个链接的指针,该链接从未设置,包含垃圾:

ptr = ptr->Next_Price;

在这里,您丢弃该值,为下一个节点分配空间,但您永远不会将其作为链接存储在前一个节点中:

ptr = (Price*) malloc (sizeof(Price));

切换顺序:

ptr->Next_Price = (Price*) malloc (sizeof(Price));
ptr = ptr->Next_Price;

开始时的另一个问题:您尝试存储头节点 ( Price *ptr1 = ptr;),但此时ptr为 NULL。

选择一个调试器,并逐步完成您的程序。在未来的某个时候,您应该能够在脑海中(或用纸和铅笔)做同样的事情,但现在您似乎正在为一些基本概念而苦苦挣扎……因此,将现实与您的事物进行比较的最佳方法认为您的程序所做的就是在调试器中运行它。

于 2013-06-30T11:06:58.207 回答