BCA TU, C Programming – Unit 10: Structure

Structures and unions are user-defined data types that allow grouping of different types of data under a single name.


1. Structure

  • Declaration:

struct Student {

    int id;

    char name[20];

    float marks;

};

  • Initialization:

struct Student s1 = {1, “Alice”, 85.5};

  • Access members using dot operator (.):

printf(“%s”, s1.name);


2. Nested Structure

  • Structure inside another structure.

struct Date {

    int day, month, year;

};

struct Student {

    char name[20];

    struct Date dob;

};


3. Array of Structure

  • Store multiple structure variables.

struct Student s[3];

s[0].id = 1;


4. Array within Structure

  • Structure can have arrays as members.

struct Student {

    char name[20];

    int marks[5];

};


5. Passing Structure & Array of Structure to Functions

  • By Value: Copies data; original structure unchanged.
  • By Reference (using pointers): Allows modification of original data.

void printStudent(struct Student s);

void updateMarks(struct Student *s);


6. Structure & Pointer

  • Access members using arrow operator (->).

struct Student *ptr = &s1;

printf(“%s”, ptr->name);


7. Bit Fields

  • Allows storing data using a specific number of bits.

struct Flags {

    unsigned int isAdmin:1;

    unsigned int isGuest:1;

};


8. Union and Its Importance

  • Union stores different types in the same memory location. Only one member can hold a value at a time.

union Data {

    int i;

    float f;

    char c;

};

  • Useful to save memory.

9. Structure vs Union

FeatureStructureUnion
MemorySeparate for each memberShared memory for all members
AccessAll members simultaneouslyOnly one member at a time
SizeSum of sizes of all membersSize of largest member
Use CaseStore different data togetherSave memory when only one value is needed

Key Takeaways

  • Structures group different data types; unions share memory among members.
  • Nested structures and arrays inside structures provide flexibility.
  • Use pointers to structures for efficient function calls and memory access.
  • Bit fields save memory by using specific bits for flags.
  • Arrays of structures are useful for storing multiple records.
  • Structure vs Union: choose union to save memory when only one value is needed.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.