SlideShare a Scribd company logo
C structures
     and unions

1
C structures: aggregate, yet scalar
       aggregate in that they hold multiple data items at one
        time
           named members hold data items of various types
           like the notion of class/field in C or C++
            – but without the data hiding features
       scalar in that C treats each structure as a unit
           as opposed to the “array” approach: a pointer to a collection
            of members in memory
           entire structures (not just pointers to structures) may be
            passed as function arguments, assigned to variables, etc.
           Interestingly, they cannot be compared using ==
            (rationale: too inefficient)


    2
Structure declarations
       Combined variable and type declaration
struct tag {member-list} variable-list;
       Any one of the three portions can be omitted

struct {int a, b; char *p;} x, y;                                /* omit tag */
           variables x, y declared with members as described:
            int members a, b and char pointer p.
           x and y have same type, but differ from all others –
            even if there is another declaration:
            struct {int a, b; char *p;} z;
            /* z has different type from x, y */



    3                         CS 3090: Safety Critical Programming in C
Structure declarations
struct S {int a, b; char *p;};                            /* omit variables */
       No variables are declared, but there is now a type struct
        S that can be referred to later


struct S z;             /* omit members */
           Given an earlier declaration of struct S, this declares a
            variable of that type

typedef struct {int a, b; char *p;} S;
  /* omit both tag and variables */
           This creates a simple type name S
            (more convenient than struct S)

    4                         CS 3090: Safety Critical Programming in C
Recursively defined structures
       Obviously, you can’t have a structure that contains an
        instance of itself as a member – such a data item would
        be infinitely large
       But within a structure you can refer to structures of the
        same type, via pointers
struct TREENODE {
  char *label;
  struct TREENODE *leftchild, *rightchild;
}




    5                     CS 3090: Safety Critical Programming in C
Recursively defined structures
       When two structures refer to each other, one must be
        declared in incomplete (prototype) fashion
struct HUMAN;
struct PET {
  char name[NAME_LIMIT];
  char species[NAME_LIMIT];
  struct HUMAN *owner;
} fido = {″Fido″, ″Canis lupus familiaris″};
struct HUMAN {
  char name[NAME_LIMIT];
                              We can’t initialize the owner member
  struct PET pets[PET_LIMIT];               at this point,
} sam = {″Sam″, {fido}};        since it hasn’t been declared yet


    6                    CS 3090: Safety Critical Programming in C
Member access
         Direct access operator s.m
             subscript and dot operators have same precedence and
              associate left-to-right, so we don’t need parentheses for
              sam.pets[0].species
         Indirect access s->m: equivalent to (*s).m
           Dereference a pointer to a structure, then return a member of
            that structure
           Dot operator has higher precedence than indirection operator
            , so parentheses are needed in (*s).m
          (*fido.owner).name                  or     fido.owner->name

   . evaluated first: access owner member                    . and -> have equal precedence
* evaluated next: dereference pointer to HUMAN                     and associate left-to-right
      7                         CS 3090: Safety Critical Programming in C
Memory layout
struct COST { int amount;
                 char currency_type[2]; }
struct PART { char id[2];
                 struct COST cost;
                 int num_avail; }
layout of struct PART:
                                      currency_type


     id                amount                                       num_avail

                               cost
Here, the system uses 4-byte alignment of integers,
so amount and num_avail must be aligned
Four bytes wasted for each structure!

 8                      CS 3090: Safety Critical Programming in C
Memory layout
A better alternative (from a space perspective):
struct COST { int amount;
              char currency_type; }
struct PART { struct COST cost;
              char id[2];
              int num_avail;
}
                      currency_type


      amount               id          num_avail
            cost



 9                    CS 3090: Safety Critical Programming in C
Bit fields                    Bit field members must be ints

    If space is a serious concern, you can select the number
     of bits used for each member
struct CHAR { unsigned ch: 7;
                                    Note: This won’t work on
              unsigned font: 6;     machines with 16-bit ints
              unsigned size: 19; };
Layout possibilities (machine-dependent):


            ch      font                                           size



                                    size              font          ch


    10                 CS 3090: Safety Critical Programming in C
Bit fields
    Portability is an issue:
        Do any bit field sizes exceed the machine’s int size?
        Is there any pointer manipulation in your code that assumes a
         particular layout?
    Bit fields are “syntactic sugar” for more complex shifting/
     masking
        e.g. to get font value, mask off the ch and size bits, then shift
         right by 19
        This is what actually happens in the object code –
         bit fields just make it look simpler at the source level



    11                      CS 3090: Safety Critical Programming in C
Structures as function arguments
    Structures are scalars, so they can be returned and
     passed as arguments – just like ints, chars
struct BIG changestruct(struct BIG s);
        Call by value: temporary copy of structure is created
        Caution: passing large structures is inefficient
         – involves a lot of copying
    avoid by passing a pointer to the structure instead:
void changestruct(struct BIG *s);
    What if the struct argument is read-only?
        Safe approach: use const
void changestruct(struct BIG const *s);


    12                     CS 3090: Safety Critical Programming in C
Unions
    Like structures, but every member occupies the same
     region of memory!
        Structures: members are “and”ed together: “name and species
         and owner”
        Unions: members are “xor”ed together

union VALUE {
   float f;
   int i;
   char *s;
};
/* either a float xor an int xor a string */

    13                    CS 3090: Safety Critical Programming in C
Unions
    Up to programmer to determine how to interpret a
     union (i.e. which member to access)
    Often used in conjunction with a “type” variable that
     indicates how to interpret the union value

enum TYPE { INT, FLOAT, STRING };
struct VARIABLE {
   enum TYPE type;             Access type to determine
   union VALUE value;           how to interpret value
};




    14                 CS 3090: Safety Critical Programming in C
Unions
    Storage
        size of union is the size of its largest member
        avoid unions with widely varying member sizes;
         for the larger data types, consider using pointers instead
    Initialization
        Union may only be initialized to a value appropriate for the
         type of its first member




    15                      CS 3090: Safety Critical Programming in C
Ad

Recommended

PPTX
Presentation on c structures
topu93
 
PPTX
Type casting in c programming
Rumman Ansari
 
PPTX
Parameter passing to_functions_in_c
ForwardBlog Enewzletter
 
PPT
Pointers C programming
Appili Vamsi Krishna
 
PPTX
Functions in C
Kamal Acharya
 
PPT
Union In language C
Ravi Singh
 
PDF
Constructor and Destructor
Kamal Acharya
 
PDF
Constructors and Destructors
Dr Sukhpal Singh Gill
 
PPTX
Structure in c language
sangrampatil81
 
PPTX
Functions in c language
tanmaymodi4
 
PPTX
Tokens in C++
Mahender Boda
 
PPTX
Union in C programming
Kamal Acharya
 
PDF
Pointers
sarith divakar
 
PPTX
Typedef
vaseemkhn
 
PPTX
Operator overloading
Burhan Ahmed
 
PPTX
This pointer
Kamal Acharya
 
PPT
structure and union
student
 
PDF
Class and object
Prof. Dr. K. Adisesha
 
PPTX
C Structures and Unions
Dhrumil Patel
 
PPTX
Pointer in c
Imamul Kadir
 
PDF
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
PDF
04. constructor & destructor
Haresh Jaiswal
 
PPT
File handling in c
David Livingston J
 
PPTX
Type conversion
PreethaPreetha5
 
PPTX
C programming - String
Achyut Devkota
 
PPTX
C Programming: Structure and Union
Selvaraj Seerangan
 
PPTX
classes and objects in C++
HalaiHansaika
 
PPT
C Structures & Unions
Ram Sagar Mourya
 
PPT
structures and unions in 'C'
illpa
 

More Related Content

What's hot (20)

PPTX
Structure in c language
sangrampatil81
 
PPTX
Functions in c language
tanmaymodi4
 
PPTX
Tokens in C++
Mahender Boda
 
PPTX
Union in C programming
Kamal Acharya
 
PDF
Pointers
sarith divakar
 
PPTX
Typedef
vaseemkhn
 
PPTX
Operator overloading
Burhan Ahmed
 
PPTX
This pointer
Kamal Acharya
 
PPT
structure and union
student
 
PDF
Class and object
Prof. Dr. K. Adisesha
 
PPTX
C Structures and Unions
Dhrumil Patel
 
PPTX
Pointer in c
Imamul Kadir
 
PDF
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
PDF
04. constructor & destructor
Haresh Jaiswal
 
PPT
File handling in c
David Livingston J
 
PPTX
Type conversion
PreethaPreetha5
 
PPTX
C programming - String
Achyut Devkota
 
PPTX
C Programming: Structure and Union
Selvaraj Seerangan
 
PPTX
classes and objects in C++
HalaiHansaika
 
Structure in c language
sangrampatil81
 
Functions in c language
tanmaymodi4
 
Tokens in C++
Mahender Boda
 
Union in C programming
Kamal Acharya
 
Pointers
sarith divakar
 
Typedef
vaseemkhn
 
Operator overloading
Burhan Ahmed
 
This pointer
Kamal Acharya
 
structure and union
student
 
Class and object
Prof. Dr. K. Adisesha
 
C Structures and Unions
Dhrumil Patel
 
Pointer in c
Imamul Kadir
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
04. constructor & destructor
Haresh Jaiswal
 
File handling in c
David Livingston J
 
Type conversion
PreethaPreetha5
 
C programming - String
Achyut Devkota
 
C Programming: Structure and Union
Selvaraj Seerangan
 
classes and objects in C++
HalaiHansaika
 

Similar to C Structures And Unions (20)

PPT
C Structures & Unions
Ram Sagar Mourya
 
PPT
structures and unions in 'C'
illpa
 
PPT
Oop lec 3(structures)
Asfand Hassan
 
PPTX
Structure
Rokonuzzaman Rony
 
PPTX
Module 5-Structure and Union
nikshaikh786
 
PDF
Structures
arshpreetkaur07
 
PPTX
structenumtypedefunion.pptx
KUPPALAPADMINI
 
PDF
03 structures
Rajan Gautam
 
PDF
slideset 7 structure and union (1).pdf
HimanshuKansal22
 
PPTX
M-2-Pointers-2.pptx by engineering institutions
sreeanu110405
 
PPT
Advanced+pointers
Rubal Bansal
 
PPTX
Chapter 8 Structure Part 2 (1).pptx
Abhishekkumarsingh630054
 
PPT
Programming Fundamentals C++ Basics ES 036
tivilar649
 
PDF
C++_notes.pdf
HimanshuSharma997566
 
PPT
C Language_PPS_3110003_unit 8ClassPPT.ppt
NikeshaPatel1
 
PPTX
IT LAB Presentation (Aditya Sharma 23EEACS005).pptx
chabriislive
 
PDF
Unit 4 qba
Sowri Rajan
 
PDF
C structure and union
Thesis Scientist Private Limited
 
PPT
C introduction
MadhuriPareek
 
PDF
structure1.pdf
AbhimanyuKumarYadav3
 
C Structures & Unions
Ram Sagar Mourya
 
structures and unions in 'C'
illpa
 
Oop lec 3(structures)
Asfand Hassan
 
Module 5-Structure and Union
nikshaikh786
 
Structures
arshpreetkaur07
 
structenumtypedefunion.pptx
KUPPALAPADMINI
 
03 structures
Rajan Gautam
 
slideset 7 structure and union (1).pdf
HimanshuKansal22
 
M-2-Pointers-2.pptx by engineering institutions
sreeanu110405
 
Advanced+pointers
Rubal Bansal
 
Chapter 8 Structure Part 2 (1).pptx
Abhishekkumarsingh630054
 
Programming Fundamentals C++ Basics ES 036
tivilar649
 
C++_notes.pdf
HimanshuSharma997566
 
C Language_PPS_3110003_unit 8ClassPPT.ppt
NikeshaPatel1
 
IT LAB Presentation (Aditya Sharma 23EEACS005).pptx
chabriislive
 
Unit 4 qba
Sowri Rajan
 
C structure and union
Thesis Scientist Private Limited
 
C introduction
MadhuriPareek
 
structure1.pdf
AbhimanyuKumarYadav3
 
Ad

More from Ram Sagar Mourya (11)

DOC
A must Sql notes for beginners
Ram Sagar Mourya
 
PPT
There Is Always A Better Way
Ram Sagar Mourya
 
PPS
Attitude
Ram Sagar Mourya
 
PPS
3 Things In Our Life
Ram Sagar Mourya
 
DOC
Microsoft Word Shortcut Keys
Ram Sagar Mourya
 
DOC
Apple Macintosh Shortcut Keys
Ram Sagar Mourya
 
PDF
Discrete Mathematics - Mathematics For Computer Science
Ram Sagar Mourya
 
PPT
.net framework
Ram Sagar Mourya
 
DOC
Asp.Net Tutorials
Ram Sagar Mourya
 
DOC
Asp.Net The Data List Control
Ram Sagar Mourya
 
DOC
Asp.Net Database
Ram Sagar Mourya
 
A must Sql notes for beginners
Ram Sagar Mourya
 
There Is Always A Better Way
Ram Sagar Mourya
 
3 Things In Our Life
Ram Sagar Mourya
 
Microsoft Word Shortcut Keys
Ram Sagar Mourya
 
Apple Macintosh Shortcut Keys
Ram Sagar Mourya
 
Discrete Mathematics - Mathematics For Computer Science
Ram Sagar Mourya
 
.net framework
Ram Sagar Mourya
 
Asp.Net Tutorials
Ram Sagar Mourya
 
Asp.Net The Data List Control
Ram Sagar Mourya
 
Asp.Net Database
Ram Sagar Mourya
 
Ad

Recently uploaded (20)

PPTX
Essar at IEW 2025, Leading the Way to India’s Green Energy Transition.
essarcase
 
PDF
How Effective Leadership Drives Success and Accelerates Business Growth by De...
Devin Doyle
 
PDF
Paul Turovsky - A Key Contributor
Paul Turovsky
 
PDF
Easy Solar Calculator for Homeowners : ksquare energy
Ksquare Energy Pvt. Ltd.
 
PPTX
The Strategic Landscape of Essar’s CSR Initiatives in 2024
essarupdate
 
PPTX
Appreciations - June 25.pptxggggggghhhhhh
anushavnayak
 
PDF
Oleksandr Osypenko: Управління обсягом (Scope) (UA)
Lviv Startup Club
 
PDF
Netflix Social Watchlists Business Proposal
lexarofficial222
 
PDF
Hire the Best Crypto Recovery Experts for Fast Recovery in 2025: Puran Crypto...
henryywalker3
 
PDF
The APCO Geopolitical Radar Q3 2025 Edition
APCO
 
PPTX
Vaden Consultancy: Transforming Businesses with Integrated HR, IT, and Cloud ...
Vaden Consultancy
 
PPTX
Axcess Instruments Pitch Deck - Newport Beach Investor Conference 2025
Hector Del Castillo, CPM, CPMM
 
PDF
Power of the Many: Digital Energy Masterclass
mariana491193
 
PDF
Enterprise Architecture Professional Journal Vol IX June 2025.pdf
Darryl_Carr
 
PDF
The Future State Of Work - Actionable Summary for Startup Founders
vikram sood
 
PPTX
Recovered Paper Market Size, Share & Forecast 2034
Expert Market Research
 
PPTX
Improving Sales Forecasting in Volatile B2B Capital Equipment Markets - Dave ...
Dave Litwiller
 
PDF
AX to Dynamics 365 Finance and Operations in USA.pdf
Trident information system
 
PPTX
QuickBooks Keeps Freezing: Causes & Solutions.pptx
robastwilliams
 
PPTX
Akční plán pro chemický průmysl - Ivan Souček
pavelborek
 
Essar at IEW 2025, Leading the Way to India’s Green Energy Transition.
essarcase
 
How Effective Leadership Drives Success and Accelerates Business Growth by De...
Devin Doyle
 
Paul Turovsky - A Key Contributor
Paul Turovsky
 
Easy Solar Calculator for Homeowners : ksquare energy
Ksquare Energy Pvt. Ltd.
 
The Strategic Landscape of Essar’s CSR Initiatives in 2024
essarupdate
 
Appreciations - June 25.pptxggggggghhhhhh
anushavnayak
 
Oleksandr Osypenko: Управління обсягом (Scope) (UA)
Lviv Startup Club
 
Netflix Social Watchlists Business Proposal
lexarofficial222
 
Hire the Best Crypto Recovery Experts for Fast Recovery in 2025: Puran Crypto...
henryywalker3
 
The APCO Geopolitical Radar Q3 2025 Edition
APCO
 
Vaden Consultancy: Transforming Businesses with Integrated HR, IT, and Cloud ...
Vaden Consultancy
 
Axcess Instruments Pitch Deck - Newport Beach Investor Conference 2025
Hector Del Castillo, CPM, CPMM
 
Power of the Many: Digital Energy Masterclass
mariana491193
 
Enterprise Architecture Professional Journal Vol IX June 2025.pdf
Darryl_Carr
 
The Future State Of Work - Actionable Summary for Startup Founders
vikram sood
 
Recovered Paper Market Size, Share & Forecast 2034
Expert Market Research
 
Improving Sales Forecasting in Volatile B2B Capital Equipment Markets - Dave ...
Dave Litwiller
 
AX to Dynamics 365 Finance and Operations in USA.pdf
Trident information system
 
QuickBooks Keeps Freezing: Causes & Solutions.pptx
robastwilliams
 
Akční plán pro chemický průmysl - Ivan Souček
pavelborek
 

C Structures And Unions

  • 1. C structures and unions 1
  • 2. C structures: aggregate, yet scalar  aggregate in that they hold multiple data items at one time  named members hold data items of various types  like the notion of class/field in C or C++ – but without the data hiding features  scalar in that C treats each structure as a unit  as opposed to the “array” approach: a pointer to a collection of members in memory  entire structures (not just pointers to structures) may be passed as function arguments, assigned to variables, etc.  Interestingly, they cannot be compared using == (rationale: too inefficient) 2
  • 3. Structure declarations  Combined variable and type declaration struct tag {member-list} variable-list;  Any one of the three portions can be omitted struct {int a, b; char *p;} x, y; /* omit tag */  variables x, y declared with members as described: int members a, b and char pointer p.  x and y have same type, but differ from all others – even if there is another declaration: struct {int a, b; char *p;} z; /* z has different type from x, y */ 3 CS 3090: Safety Critical Programming in C
  • 4. Structure declarations struct S {int a, b; char *p;}; /* omit variables */  No variables are declared, but there is now a type struct S that can be referred to later struct S z; /* omit members */  Given an earlier declaration of struct S, this declares a variable of that type typedef struct {int a, b; char *p;} S; /* omit both tag and variables */  This creates a simple type name S (more convenient than struct S) 4 CS 3090: Safety Critical Programming in C
  • 5. Recursively defined structures  Obviously, you can’t have a structure that contains an instance of itself as a member – such a data item would be infinitely large  But within a structure you can refer to structures of the same type, via pointers struct TREENODE { char *label; struct TREENODE *leftchild, *rightchild; } 5 CS 3090: Safety Critical Programming in C
  • 6. Recursively defined structures  When two structures refer to each other, one must be declared in incomplete (prototype) fashion struct HUMAN; struct PET { char name[NAME_LIMIT]; char species[NAME_LIMIT]; struct HUMAN *owner; } fido = {″Fido″, ″Canis lupus familiaris″}; struct HUMAN { char name[NAME_LIMIT]; We can’t initialize the owner member struct PET pets[PET_LIMIT]; at this point, } sam = {″Sam″, {fido}}; since it hasn’t been declared yet 6 CS 3090: Safety Critical Programming in C
  • 7. Member access  Direct access operator s.m  subscript and dot operators have same precedence and associate left-to-right, so we don’t need parentheses for sam.pets[0].species  Indirect access s->m: equivalent to (*s).m  Dereference a pointer to a structure, then return a member of that structure  Dot operator has higher precedence than indirection operator , so parentheses are needed in (*s).m (*fido.owner).name or fido.owner->name . evaluated first: access owner member . and -> have equal precedence * evaluated next: dereference pointer to HUMAN and associate left-to-right 7 CS 3090: Safety Critical Programming in C
  • 8. Memory layout struct COST { int amount; char currency_type[2]; } struct PART { char id[2]; struct COST cost; int num_avail; } layout of struct PART: currency_type id amount num_avail cost Here, the system uses 4-byte alignment of integers, so amount and num_avail must be aligned Four bytes wasted for each structure! 8 CS 3090: Safety Critical Programming in C
  • 9. Memory layout A better alternative (from a space perspective): struct COST { int amount; char currency_type; } struct PART { struct COST cost; char id[2]; int num_avail; } currency_type amount id num_avail cost 9 CS 3090: Safety Critical Programming in C
  • 10. Bit fields Bit field members must be ints  If space is a serious concern, you can select the number of bits used for each member struct CHAR { unsigned ch: 7; Note: This won’t work on unsigned font: 6; machines with 16-bit ints unsigned size: 19; }; Layout possibilities (machine-dependent): ch font size size font ch 10 CS 3090: Safety Critical Programming in C
  • 11. Bit fields  Portability is an issue:  Do any bit field sizes exceed the machine’s int size?  Is there any pointer manipulation in your code that assumes a particular layout?  Bit fields are “syntactic sugar” for more complex shifting/ masking  e.g. to get font value, mask off the ch and size bits, then shift right by 19  This is what actually happens in the object code – bit fields just make it look simpler at the source level 11 CS 3090: Safety Critical Programming in C
  • 12. Structures as function arguments  Structures are scalars, so they can be returned and passed as arguments – just like ints, chars struct BIG changestruct(struct BIG s);  Call by value: temporary copy of structure is created  Caution: passing large structures is inefficient – involves a lot of copying  avoid by passing a pointer to the structure instead: void changestruct(struct BIG *s);  What if the struct argument is read-only?  Safe approach: use const void changestruct(struct BIG const *s); 12 CS 3090: Safety Critical Programming in C
  • 13. Unions  Like structures, but every member occupies the same region of memory!  Structures: members are “and”ed together: “name and species and owner”  Unions: members are “xor”ed together union VALUE { float f; int i; char *s; }; /* either a float xor an int xor a string */ 13 CS 3090: Safety Critical Programming in C
  • 14. Unions  Up to programmer to determine how to interpret a union (i.e. which member to access)  Often used in conjunction with a “type” variable that indicates how to interpret the union value enum TYPE { INT, FLOAT, STRING }; struct VARIABLE { enum TYPE type; Access type to determine union VALUE value; how to interpret value }; 14 CS 3090: Safety Critical Programming in C
  • 15. Unions  Storage  size of union is the size of its largest member  avoid unions with widely varying member sizes; for the larger data types, consider using pointers instead  Initialization  Union may only be initialized to a value appropriate for the type of its first member 15 CS 3090: Safety Critical Programming in C