Thread: A simple question on structures

  1. #1
    Registered User
    Join Date
    Jan 2011

    A simple question on structures

    Can you please tell me the difference between these

    typedef struct aStructure
             int a;
    } object;
    typedef struct
         int a;
    } aStructure;
    struct aStructure
           int a;
    } obj;
    I am a bit confused..

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    segmentation fault
    The first one is a typedef'd struct; the type is "object", and it is defined as a struct aStructure. The second one is the same, except the struct is anonymous, because it does not need a name if it is always going to used via the typedef (in this case "aStructure"). A common situation where the struct does need a name is if it requires an internal pointer to itself, eg:

    typedef struct aStructure
             int a;
             struct aStructure *p;
    } object;
    Linked lists work this way; the issue is you cannot use the typedef name ("object *p") inside the definition unless the definition follows the declaration:

    struct astruct;
    typedef struct astruct object;
    struct eg {
    	object *p;
    In which case you need a named struct anyway.

    The third one is a struct definition which includes an instantiation, "obj". Ie, obj is a variable of type struct astructure. This is a little confusing because the first two examples, with the typedefs, use the same notation to name the typedef.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Little question about structures...
    By mfm12002 in forum C Programming
    Replies: 4
    Last Post: 12-17-2009, 04:05 PM
  2. Pointers and Data Structures (Simple Question, I think)
    By Flamefury in forum C Programming
    Replies: 16
    Last Post: 11-23-2009, 12:17 AM
  3. Question on Structures in C - a different one
    By gvs in forum C Programming
    Replies: 5
    Last Post: 02-09-2005, 02:23 AM
  4. Structures: a yes/no question.
    By Matt13 in forum C Programming
    Replies: 2
    Last Post: 07-29-2004, 08:33 AM
  5. Question about structures
    By Randoon in forum C Programming
    Replies: 2
    Last Post: 12-12-2002, 11:47 PM

Tags for this Thread