Click here to Skip to main content
15,867,975 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,
i am trying to make a linked list code library, here is what i have done so far,

C++
struct node
{
   int32 data;   //store data informatino
   struct node *next;   //reference to next node
};

typedef struct
{
   struct node *head;
   int count;
}llist;

void list_add(llist *list, int32 element)
{
   unsigned int32 count;
   struct node* temp;
   struct node *new = null;
   new = malloc(sizeof(struct node));
   
   new -> data = element;
   new -> next = null;
   if(list -> head == null)
      list -> head = new;
   else
   {
      temp = list -> head;
      while(temp != null)
      {
         count++;
         temp = temp -> next;
      }
      temp -> next = new;
   }
}

int32 list_sum(llist *list)
{
   int32 total;
   struct node* temp;
   
   temp = list -> head;
   while(temp != null)
   {
      temp = temp -> next;
      total += temp -> data;
   }
   return total;
}


i have 2 question when i have a struct with a member of another struct, say a(b,x,y), b(x,y)
how to call it for example (a.b.x)

and also i would like to get review to my coding,

Thanks in advance,
z3ngew
Posted

1 solution

Your code contains some obvious glitches.
C++
struct node *new = null;
new = malloc(sizeof(struct node));

That is overdoing it with "safe" programming. You don't need to initialize the new pointer if you are going to assign to it in the very next statement.

Besides, the name new is not a good choice, because it is a keyword in C++. Some time later you want to upgrade to C++ and find that you have to edit a lot of places.
C++
temp = list -> head;
 while(temp != null)
 {
    count++;
    temp = temp -> next;
 }
 temp -> next = new;

count is not used anywhere else, so you can throw it out. And you actually never use the count member of your llist structure.

The while loop runs one iteration too much. It runs until temp is NULL and then you try to assign to temp->next. That won't work.

And finally:
C++
temp = list -> head;
 while(temp != null)
 {
    temp = temp -> next;
    total += temp -> data;
 }

You need to exchange the two statements inside the loop. You want to first access temp->data and then move on to the next node.

Your first question:

If you have
C++
struct A
{
   int x;
   int y;
};

struct B
{
   struct A aaa;
   int z;
};

And pB is a pointer to a B, then you would access x by: pB->aaa.x.
 
Share this answer
 
Comments
z3ngew 6-Sep-13 12:01pm    
many thanks my freind
Sergey Alexandrovich Kryukov 6-Sep-13 12:19pm    
Good catch, a 5.
—SA
nv3 6-Sep-13 12:55pm    
Thanks you, Sergey!
Menon Santosh 6-Sep-13 14:14pm    
my +5
nv3 6-Sep-13 15:06pm    
Thanks Menon!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900