0

I have following code:

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);

The problem is the values are correctly assigned to ptr but not to ptr1. I have already pointed the beginning of the node with ptr1:

Price *ptr1 = ptr;

Here is the struct definition:

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

I am toatally fed up with what went wrong..any idea??

cosmos
  • 2,263
  • 1
  • 17
  • 30

1 Answers1

0

You haven't created a linked list, many problems in the code:

Just take this one:

You retrieve here the pointer for the next link, which was never set, contains garbage:

ptr = ptr->Next_Price;

Here you discard that value, allocate space for the next node, but you never store it as a link in the previous node:

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

Switch the order:

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

Another problem right at the beginng: You try to store the head node (Price *ptr1 = ptr;), but at that point ptr is NULL.

Pick a debugger, and go through your program step-by-step. At some point in the future you should be able to do the same thing in your head (or with paper&pencil) but looks like at the moment you're struggling with some basic concepts... so the best way to compare reality with what you think your program does is to run it in a debugger.

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • yes, was just updating.. I guess there are more problems, but let's leave the rest for him as an exercise. – Karoly Horvath Jun 30 '13 at 11:15
  • Thanks, got it working now..one problem you already mentioned above.. secondly, for assignment of ptr to ptr1 I need to assign it after first malloc. This is a very small part of very long assignment..working for hours made my mind so blank that I forgot a basic concept that Malloc returns a new address.. anyhow, thanks for the help..!! – cosmos Jun 30 '13 at 11:24