Thread: Difference between . and ->

  1. #1
    Registered User
    Join Date
    Jul 2009
    Posts
    5

    Difference between . and ->

    Hi there,

    I am just trying to learn how to make linked lists and have made the following function:

    Code:
    list* addList()  {
        list* firstList = NULL;
    	list* newList = malloc(sizeof(list));
    	newList -> count = 128;
    	newList -> next = firstList;
    	
    	return newList;
    }
    This works fine and when I have the following printf statement:

    Code:
    list* bigList = addList();
    printf("%d\n", bigList -> count);
    then 128 gets printed out, as I hoped it would.

    My question is that when I try the following printf instead:

    Code:
    printf("%d\n", bigList.count);
    then I get an error saying that a struct is required. As I understand it, my addList() function returns a pointer to the list element labeled newList in the function. This list element has a member called count. So why is it that I can't use the membership operator '.' in this case? And what is the essential difference between '.' and '->'?

    Many thanks in advance.

    Joe

  2. #2
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    -> requires pointer to the structure on it's left side, whereas the '.' operator requires a structure variable on it's left side not a pointer.
    Eg.
    Code:
    struct book
    {
    int page;
    char name;
    float price}b1;
    b1.page //correct
    b1->price //incorrect
    HOPE YOU UNDERSTAND.......

    By associating with wise people you will become wise yourself
    It's fine to celebrate success but it is more important to heed the lessons of failure
    We've got to put a lot of money into changing behavior


    PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
    IDE- Microsoft Visual Studio 2008 Express Edition

  3. #3
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Or a union.

  4. #4
    Registered User
    Join Date
    Jul 2009
    Posts
    5
    Excellent. Thank you Ben10 for the explanation. I understand now.

    Cheers WhiteFlags.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. small -> big -> bigger -> bigger than bigger -> ?
    By happyclown in forum A Brief History of Cprogramming.com
    Replies: 9
    Last Post: 03-11-2009, 12:12 PM
  2. Dev-C++ -> Tools - > Editor -> Syntax
    By Yuri2 in forum C++ Programming
    Replies: 19
    Last Post: 07-03-2006, 07:48 AM
  3. > > > Urgent Help < < <
    By CodeCypher in forum C Programming
    Replies: 2
    Last Post: 01-31-2006, 02:06 PM
  4. Difference between '->' and '.'
    By Mystic_Skies in forum C Programming
    Replies: 2
    Last Post: 11-20-2004, 10:45 PM
  5. Difference Tab -> Algebra
    By (TNT) in forum A Brief History of Cprogramming.com
    Replies: 2
    Last Post: 03-10-2002, 05:57 PM