Skip to study material
← Question index

QUESTION 02

Explain user-defined structure types, declaration and member access.

5 marks

Answer in brief

A structure represents related data as one record, such as a student’s roll number and marks.

Declaration

struct Student {
    int roll;
    double marks;
};
struct Student s = {101, 87.5};

Members and access

The tag Student names the structure type. The definition lists an int member roll and a double member marks. s is an object of that type. Use s.roll and s.marks to select its members. A member assignment such as s.marks = 90.0 changes only that member of s.

Why structures are useful

  1. Keep related values together instead of maintaining unrelated variables.
  2. Pass or return a complete record in a function interface.
  3. Create arrays of records for students, products or employees.
  4. Combine structures with pointers to build linked data structures.

Initialisation and storage

The braces supply initial values in member order. A designated initialiser, such as {.marks = 87.5, .roll = 101}, can name members explicitly. Storage may include padding for alignment, so sizeof(struct Student) need not equal the sum of the written member sizes. Do not assume a fixed byte layout across computers.

Complexity

Accessing a fixed member takes O(1) work. Processing n records generally requires O(n) traversal work. Structure definition alone does not execute input or output; the program must read and display members explicitly.

Diagram or flowchart

CodeBhavya illustration of structure
Explain user-defined structure types, declaration and member access. · Download diagram

Complete C example

main.c

Download main.c
/* CodeBhavya | Data Structures AR25 | Learning example */
#include <stdio.h>
struct Student { int roll; double marks; };

int main(void)
{
    struct Student s = {101, 87.5};
    printf("Roll = %d, marks = %.1f\n", s.roll, s.marks);
    return 0;
}

Sample input and output

The example uses values in the code.

Output

Roll = 101, marks = 87.5