empty structure in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • 333471
    New Member
    • Jun 2014
    • 4

    empty structure in C

    Can a blank struct b declared
    · Can an array of blank struct b declared
    · If yes what does a[3] point to
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Have you tried this?

    When you declare a struct, this is valid:

    struct data
    {
    };

    Code:
    int main()
    {
       struct data var;
       
       struct data* ptr = &var;
    }
    That is, you are allowed to define a pointer to a struct object. This requires that there be a struct object so you can put its address in the pointer. This, in turn, requires that there be a struct object of at least one byte so you can get the address.

    Comment

    • androidapp
      New Member
      • Jun 2014
      • 10

      #3
      It points to first address of the array.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        It's better to say the pointer contains "the address of element 0".

        Also, a[3] is not a pointer. It is really the element at the location of "the address of element 0 plus 3 times the sizeof the struct." That would be the 4th element of the array.

        Comment

        • donbock
          Recognized Expert Top Contributor
          • Mar 2008
          • 2427

          #5
          A struct or union declaration that does not identify any internal fields is an incomplete type. The compiler knows the name of the incomplete type, but it does not know the size of the incomplete type; thus, you cannot declare variables of that type (including arrays of that type) nor can an incomplete type be passed to sizeof. You can, however, declare pointers to an incomplete type. Declaration of an incomplete type is frequently followed by a redeclaration of that type that identifies the internal fields. This completes the type.

          What good is an incomplete type?

          It is helpful for declaring linked lists. The following snippet could not declare the link without the incomplete type declaration.
          Code:
          struct node;
          struct node { struct node *link; int payload };
          It is helpful for information hiding. Users of a service include the public header and then call the public functions. The implementation of the service includes the private header. This leaves users of the service unable to access individual fields of the structure.
          Code:
          Public header...
          struct myhandle;
          struct myhandle *getNewThing(void);
          int changeThing(struct myhandle *);
          
          Private header...
          #include "public header"
          struct myhandle {
              ...
              };

          Comment

          Working...