GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 06-Sep-2007, 12:11
aijazbaig1's Avatar
aijazbaig1 aijazbaig1 is offline
Member
 
Join Date: May 2006
Location: India
Posts: 156
aijazbaig1 has a spectacular aura aboutaijazbaig1 has a spectacular aura about

yet another linked list program


hello.
IM trying to build my second linked list and as usual im stuck at some really simple errors which I cannot seem to find.

Heres the main source file 'list.c':
CPP / C++ / C Code:
#include <stdlib.h>
#include "list.h"

int size = 0;

int main()

{
    return 0;
}

void append(list_item* head, int x)//puts x at the end of the list

     //list_item* my_item ;//the new item
{
    list_item* my_item ;//the new item
    my_item = (list_item*) (malloc)(sizeof(list_item));
    my_item -> value = x;

    if (size != 0) {
        list_item* read_head = head;
        while(read_head -> next != NULL) read_head++;//move my_item_head until we reach the last element..my_item_head now points to the last element
        (read_head -> next) = my_item;    
        my_item -> next = NULL;
        size++;
        return;
    }

    else {//the list is empty
        (head -> next) = my_item;
        my_item -> next = NULL;
        size++;
        return;
    }
}

void prepend(list_item* head, int x)//head of the list

{
    list_item* my_item ;//the new item
    my_item = (list_item*) (malloc)(sizeof(list_item));
    my_item -> value = x;

    my_item -> next = head -> next;
    head -> next = my_item;
    size++;
    return;
}

void print(list_item* head)//print the list

{
    list_item* printhead;
    printhead = head -> next;

    while (size != 0)
    //    if (printhead -> next != NULL) printf("element no. %d = %d
        for  (int i = 0;i <= size;i++) {
            printf("element no. %d = %d\n",i,printhead -> value);
            printhead = printhead -> next;
            return;
        }
    puts("nothing to print, list empty");
    return;
}

void input_sorted(list_item* head,int x)//find the first element in the list thats larger than x and put x right b4 it

{
    list_item* myitem;
    list_item* read_head;
    myitem = (list_item*)malloc(sizeof(list_item));
    myitem -> value = x;

    read_head = head -> next;//the first element in the list

    if((read_head -> next) != NULL) {
        while(((read_head -> next) -> value) <= x) {   
            read_head = read_head -> next;//navigate to the element which precedes the required element so we can insert x after this element
            if (read_head == NULL) {
                puts("there is no such element in the list");
                return;
            }
            else {
                myitem -> next = read_head -> next;
                read_head -> next = myitem;
                size++;
                return;
            }
        }
    }
    else {
        puts("there is no element in the list");
        return;
    }
}

void destroy(list_item* head)

{
    list_item* read_head = head;
    list_item* temp;
    while((read_head -> next) != NULL) {
        temp = read_head -> next;
        free(read_head);
        read_head = temp;
    }
    return;
}

Heres the header file list.h:
CPP / C++ / C Code:
#include <stdio.h>

    typedef struct list_item_ {
        int value;
        struct list_item *next;
    } list_item;

list_item* head;//head points to the first element in the list.
head->value = -1;
//list_item* tail;//tail is the end of the list.

void append(list_item*, int);//puts x at the end of the list
void prepend(list_item*, int);//head of the list
void print(list_item*);//print the list
void input_sorted(list_item*,int);//find the first element in the list thats larger than x and put x right b4 it
void destroy(list_item*);

And heres the output (the errors):
Code:
gcc -std=c99 -ggdb3 -Wall -W -pedantic -c list.c In file included from list.c:2: list.h:9: error: syntax error before '->' token list.c: In function `append': list.c:23: warning: assignment from incompatible pointer type list.c:30: warning: assignment from incompatible pointer type list.c: In function `prepend': list.c:53: warning: assignment from incompatible pointer type list.c: In function `print': list.c:62: warning: assignment from incompatible pointer type list.c:68: warning: assignment from incompatible pointer type list.c: In function `input_sorted': list.c:83: warning: assignment from incompatible pointer type list.c:86: error: dereferencing pointer to incomplete type list.c:87: warning: assignment from incompatible pointer type list.c:94: warning: assignment from incompatible pointer type list.c: In function `destroy': list.c:112: warning: assignment from incompatible pointer type *** Error code 1 make: Fatal error: Command failed for target `list.o'
What I cannot see is how in the world do they seem to have incompatible pointer types. I mean both of them are pointer to the struct of type list_item. Or are they?

Would love to hear from you guys!!
__________________
Hope to hear from you guys!

--------------------------------------------------

Best Regards,
Aijaz Baig.
  #2  
Old 06-Sep-2007, 17:00
davis
 
Posts: n/a

Re: yet another linked list program


Other than your somewhat "interesting" styles, you appear to have some difficulties in your understanding of how lists work.


Note:

while(read_head -> next != NULL) read_head++;

You can't acheive the result that you seek by incrementing the pointer!

What you need to do is:

CPP / C++ / C Code:
list_item* item = head;
while( item->next != 0 )
{
    item = item->next;
} // now item points to the last item in the list


You can't "increment" the item like you do when the storage is contiquous, as is the case in an array. Here, the "next" item may point to any address, even an address prior to the "current" item...so, incrementing an item pointer becomes a rather obvious no-no.

You also malloc, without checking to see that you are returned a valid pointer. There are a lot of other "issues" with your code, but work through them one at a time until you find them...

I strongly encourage you to follow a typical, standardize coding style. This includes the use of braces around every conditional and every looping construct even if they are "single line" and not "multi line" blocks of code. By separating your code, you also make the boundaries of your blocks clear to others.


:davis:
  #3  
Old 07-Sep-2007, 04:36
aijazbaig1's Avatar
aijazbaig1 aijazbaig1 is offline
Member
 
Join Date: May 2006
Location: India
Posts: 156
aijazbaig1 has a spectacular aura aboutaijazbaig1 has a spectacular aura about

Re: yet another linked list program


Quote:
while(read_head -> next != NULL) read_head++;

You can't acheive the result that you seek by incrementing the pointer!
Hmmm...I cannot seem to find where did I use the post-incremental operator on that pointer. May be you meant something else and I am eager to hear it from you.
Quote:
I strongly encourage you to follow a typical, standardize coding style. This includes the use of braces around every conditional and every looping construct even if they are "single line" and not "multi line" blocks of code. By separating your code, you also make the boundaries of your blocks clear to others.
Yeah this is just a very rough first draft and I have to modify it for checking NULL pointers and making it comply with certain coding styles as u mentioned in your post.
But my major concern is the issue of non.compatible types which is giving me a lot of headache and I cannot seem to understand why it is so.

Hope to hear from people,
__________________
Hope to hear from you guys!

--------------------------------------------------

Best Regards,
Aijaz Baig.
  #4  
Old 07-Sep-2007, 08:48
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,217
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: yet another linked list program


Quote:
Originally Posted by aijazbaig1
But my major concern is the issue of non.compatible
Your first major concern should be:'
Code:
list.h:9: error: syntax error before '->' token

You have an assignment statement in your header file. Since your header file is included near the beginning of your list.c file, the statement appears outside all functions. That is not allowed in C. Assignment statements must appear inside functions.

As a side note: using a global "size" variable is a terrible way to implement a linked list. Look for good examples in books or on the web. Do any of them use a global variable like "size" that is used by the list functions? See footnote.

As for all of the "incompatible pointer type" messages: your typedef is incorrect for any usage that I can think of.

You can change it to something like the following
CPP / C++ / C Code:
    typedef struct list_item_ {
        int value;
        struct list_item_ *next;
    } list_item;

or

CPP / C++ / C Code:
    typedef struct list_item {
        int value;
        struct list_item *next;
    } list_item;

Moving the assignment statement from the header file into main() and changing the typedef to one of the forms that I showed should give you something that compiles.

Regards,

Dave


Footnote:

In general it is not recommended that you include any code or data definitions in a header file that will be #included in other files. It is not "wrong" according to the rules of the language, but you will find that it leads to fatal compile errors when projects have more than one file that includes that header.

Use of global variables is also not "wrong" according to the rules of the language, and, in fact, there are places where it is appropriate to use global variables.

However...

Most experienced programmers will tell you that code that depends on inappropriate use of globals (like your "size") is an indicator of poor design. Many of us can also recall places where trying to debug anything other than trivial code (other people's code, that is) is much more difficult with globals.

If people try to give you advice for which you don't see the point, you are free to challenge it and to ignore it, of course.
  #5  
Old 07-Sep-2007, 09:25
davis
 
Posts: n/a

Re: yet another linked list program


Quote:
Originally Posted by aijazbaig1
Hmmm...I cannot seem to find where did I use the post-incremental operator on that pointer. May be you meant something else and I am eager to hear it from you.

Yeah this is just a very rough first draft and I have to modify it for checking NULL pointers and making it comply with certain coding styles as u mentioned in your post.
But my major concern is the issue of non.compatible types which is giving me a lot of headache and I cannot seem to understand why it is so.

Hope to hear from people,


Can't seem to find it? Look in the code that you posted!

CPP / C++ / C Code:
#include <stdlib.h>
#include "list.h"

int size = 0;

int main()

{
    return 0;
}

void append(list_item* head, int x)//puts x at the end of the list

     //list_item* my_item ;//the new item
{
    list_item* my_item ;//the new item
    my_item = (list_item*) (malloc)(sizeof(list_item));
    my_item -> value = x;

    if (size != 0) {
        list_item* read_head = head;
        while(read_head -> next != NULL) read_head++;//move my_item_head until we reach the last element..my_item_head now points to the last element


It shouldn't be difficult to grep for "read_head++" and you'll easily arrive at the line noted above...


:davis:
  #6  
Old 07-Sep-2007, 09:34
davis
 
Posts: n/a

Re: yet another linked list program


Quote:
Originally Posted by davekw7x
Your first major concern should be:You have an assignment statement in your header file.



When I first looked at the code, I simply commented that line out as being useless anyway. ...meaning, that even if it "did work" that it was worthless anyway in the context of a list, particularly one where the data is supposed to be a signed int and where a perfectly valid entry might be a -1 or any other valid signed int...

Rather, I chose to focus on the issues of "how a list works" rather than on the "what is needed to compile" issue(s). I find it incredibly interesting to see what elements in a body of code are tuned into by various responders.


:davis:
  #7  
Old 07-Sep-2007, 10:02
Howard_L Howard_L is online now
Regular Member
 
Join Date: Apr 2007
Location: Maryland/PA, USA
Posts: 801
Howard_L is a jewel in the roughHoward_L is a jewel in the roughHoward_L is a jewel in the rough

Re: yet another linked list program


Quote:
interesting to see what elements in a body of code are tuned into by various responders.
First thing I noticed was the empty main.... and a bunch of functions....
Now how can you write so much code with no testing? What's the fun in that?

Next it was the excess of pointers with confusing names.

Why not start with the append() and destroy() and something in main() to get going and SEE how you declarations are working out before moving on.

I have to start minimally and add on one thing at a time ,,, testing at each change.
Howard;
  #8  
Old 07-Sep-2007, 10:39
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,217
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: yet another linked list program


Quote:
Originally Posted by Howard_L
First thing I noticed was the empty main...
The first thing that I noticed was ... well lots of things other than the specific error messages.

Davis had articulated (very well) concerns about the lack of good design, and I agree with his comments.

Quote:
Originally Posted by davis
When I first looked at the code, I simply commented that line out as being useless anyway.

Sometimes when someone posts "bad code", our first reaction is to want to tell him/her to throw everything out and start all over. (And maybe that is all the advice we should give---maybe even to the extent of showing a working example with good design practices.)

However...

Sometimes it helps to know exactly where the error messages came from and what could be done to correct those particular problems.

After all is said and done, sometimes even a well-crafted design could have bits and pieces of code that would cause error messages like the ones shown in the original post. If no one had explained where they came from, then seeing them again in the future could be pretty frustrating.

I just tried to show what caused them and what could be done to correct them. Understanding why certain things don't work can be an important part of the learning process too, I'm thinking.

My statement about "your first major concern" was in direct response to the original poster's comment that the "first major concern" was the other group of error messages (since there were so many of them, I guess). My point was that all of the messages were important (and indicated fatal errors), and I would start with the first one and explain and correct each and every one. (But that's just me; I'm funny that way.)

Maybe it's not worthwhile to get "bad code" to compile without compiler errors, but once you start trying to run that code, you can (maybe) learn about what the design problems are (not to say the implementation errors), and (maybe) even learn some things about the proper way to implement a list.

Or, maybe, not...

Bottom line: People have different ways of learning and people have different ways of teaching. That's what an open forum is all about, right?


Regards,

Dave
  #9  
Old 07-Sep-2007, 11:13
davis
 
Posts: n/a

Re: yet another linked list program


Quote:
Originally Posted by Howard_L
I have to start minimally and add on one thing at a time ,,, testing at each change.

It is interesting that you bring up this point. Have you experienced XP and/or Agile or perhaps Scrum?

There are those who put forth that there should be no code written until the test for it has been written and that running the code should initially fail the test (since the code has not yet been modified to pass the test). It is an incredibly "fun" way to produce code, but it is, in my experiences, rarely adopted due to the distinct "cultural differences" compared to "conventional" coding mindsets.

Perhaps you will take a moment to try it out if you haven't already? That is, write the test first, then write the code to pass the test. That "requirement" is completed when the code successfully passes the test. The obvious benefit is that a series of tests are generated that can always be ran against the code so that one is freed of fear of change in such a way that any new changes that "break" something are quickly found when the tests are ran. Very cool in practice and very easy to adopt when the players are open-minded enough to give it a reasonable trial period.


:davis:
  #10  
Old 07-Sep-2007, 14:38
Howard_L Howard_L is online now
Regular Member
 
Join Date: Apr 2007
Location: Maryland/PA, USA
Posts: 801
Howard_L is a jewel in the roughHoward_L is a jewel in the roughHoward_L is a jewel in the rough

Re: yet another linked list program


Quote:
There are those who put forth that there should be no code written until the test for it has been written and that running the code should initially fail the test
(since the code has not yet been modified to pass the test).
Have you experienced XP and/or Agile or perhaps Scrum?
Heck no. I can barely fight my way out of a wet linked list!
I guess maybe that's the way my team works though.
(me, myself, I, and those other guys in there)

For example, when we started looking into this one (for practice) we quickly commented out everything except the structure, the main() and append(). . In our minds, it would be a waste of time to even look at anything else if that was not working properly. .

So the first task was to get a menu in main() to call an append() and freelist() working.
I (we) just had them print a line at first.
Next was to bring in the code to append() that gets a list allocated.
Next was to write a freelist().

And then I have to back up sometimes and make improvements like bringing the global 'int size' into main() and learning to pass address... (tricky)

I have been trying to do less global and macro declaration as has been suggested. It was a little tougher at first, but I'm getting better at it and with practice am continually getting a better feel for pointers and referencing...

For me printing values and comparing to what I expected really helps a lot.
It makes the screen a little trashy while building, but it's neat to see results, especially when they ARE what I expected! (sometimes)
It's like hitting a mini-lottery!

I hesitate on posting what I have. There are ,after all, MANY good examples laying around here.
But here's how I went about getting this started (using Aijaz's declarations):
CPP / C++ / C Code:
#include <stdio.h>
#include <stdlib.h>

typedef struct list_item_ {
  int value;
  struct list_item_ *next;
} list_item;

void append(list_item** head, unsigned int *size, int x);
void freeallocs(list_item* head);

int main(void)
{
  list_item* head = NULL;
  unsigned int i, c, size;
  i = c = size = 0;

  while( c != 'q') {
    printf("\nMenu: (a)ppend , (q)uit   Choice: ");
    c = getchar();
    getchar();      /* cheap cleanup of  \n */

    switch(c) {
      case 'A':
      case 'a':
        printf("You selected append... automatically allocating 5 nodes:\n");
        i=0;
        for( i = 0; i < 5; i++) {
          printf("head= %p \n", (void*)head);
          append(&head, &size, i);
          printf("    head= %p  size= %u  &size= %p \n                ---end loop %d---\n", (void*)head, size, (void*)&size, i );
        }
        break;

      case 'Q':
      case 'q':
        freeallocs(head);
        break;
    }
  }
  printf(" Does it work??? \n");
  getchar();

  return 0;
}
/********************************************************************/
void append(list_item** head, unsigned int *size, int x)
{
  list_item*  newnode;

  newnode = (list_item*)(malloc(sizeof(list_item)) );
  newnode -> value = x;            /* place the value passed from call */
  (newnode->next) = *head;
  *head = newnode;
  /* *size++;          this increments the pointer! haha */
  *size += 1;

  /* test prints: */
  printf("  size= %p  *size= %u \n", (void*)size, *size );
  printf("  *size= %u   newnode= %p,   newnode->next= %p,   head= %p \n", *size, (void*)newnode, (void*)newnode->next, (void*)*head);

  return;
}
/*******************************************************************/
void freeallocs(list_item* head)
{
  list_item* tmp;

  do {
    tmp = head->next;
    printf(" free()ing: head= %p \n", (void*)head);
    free(head);
    head = head->next;
  }
  while(tmp != NULL);
}
Anyhow, after getting comfortable with this much , ,THEN I would move into the next manipulation tasks like insert, delete etc. Doesn't everyone work this way?
Howard;
 
 

Recent GIDBlogOnce again, no time for hobbies by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Airport Log program using 3D linked List : problem reading from file batrsau C Programming Language 11 29-Feb-2008 08:44
[Include] Doubly-linked List dsmith C Programming Language 6 14-Apr-2006 14:12
linked list error message Krandygrl00 C++ Forum 4 22-Jun-2005 15:13
search linked list itsmecathys C++ Forum 20 18-Apr-2005 02:34

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 10:50.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.