Structure Assignment 2 — Initialize and Display the Details of a Student
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Initialize and Display the Details of a Student Using a Structure

📑 On this page:
  • Two Ways to Initialize
  • The Initializer Blueprint
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to initialize a structure at the point of declaration with a brace-enclosed initializer list
  • How designated initializers (C99) match members by name instead of position
  • Why the order of values in the initializer list must match the order of members
  • What happens when you provide fewer values than members (the rest are zero-filled)
  • How to format the display output so a record is readable at a glance

Two Ways to Initialize

You can initialize a structure in two distinct ways, and it matters which one you use. The first — and the one most C programmers learn first — is brace initialization at declaration: write the values in order inside curly braces, and the compiler assigns them to the members in declaration order. struct student s = {"Alice Johnson", 101, {85.5, 90.0, 78.5}}; is one line that creates a fully populated student. The outer braces correspond to the struct, and the inner braces around the marks correspond to the inner float array.

The second is designated initialization, introduced in C99. Instead of relying on order, you name each member: struct student s = {.name = "Alice Johnson", .roll = 101, .marks = {85.5, 90.0, 78.5}};. The compiler matches members by name, so you can write them in any order, skip members (they default to zero), and the code is robust to member reordering. Designated initializers are the modern C idiom for non-trivial structs.

This assignment is about initialization and display — the "before" and "after" of any real program. Once you have a populated struct, displaying it is just a matter of pulling out each member with printf and the right format specifier. The interesting part is the initialization syntax, and specifically the difference between the two styles. Both are worth knowing; both are used in real code; and the designated style is what you'll see in modern C codebases, kernel code, and any codebase that cares about maintainability.

💡 In one line: struct student s = {"Alice", 101, {85.5, 90.0, 78.5}}; fills members in order; = {.name = "Alice", .roll = 101, .marks = {85.5, 90.0, 78.5}} fills by name.

Diagram comparing two initializer syntaxes: the positional form shows values aligned with member names, the designated form shows each member with a dot-prefixed name and value

The Initializer Blueprint

The positional form is compact, but the mapping from value to member is implicit — you have to remember the member order. The designated form makes the mapping explicit.

/* Positional: values match members in order */
struct student s = {
    "Alice Johnson",       /* name  */
    101,                   /* roll  */
    {85.5, 90.0, 78.5}     /* marks */
};

/* Designated (C99): values match members by name */
struct student t = {
    .name  = "Alice Johnson",
    .roll  = 101,
    .marks = {85.5, 90.0, 78.5}
};
                                

Both produce the same struct. The positional form is shorter; the designated form is safer (reorder members in the struct, and the designated initializer still compiles correctly). The inner braces around marks are required in the positional form because marks is an array, and in the designated form you can write .marks[0] = 85.5, .marks[1] = 90.0, .marks[2] = 78.5 if you prefer, though the compact array form is fine.

Style Syntax Pros Cons
Positional {"Alice", 101, {85.5, 90.0, 78.5}} Short, widely supported (C89 onward) Values can be silently misaligned if member order changes
Designated {.name="Alice", .roll=101, .marks={85.5,90.0,78.5}} Self-documenting, robust to reordering, can skip members More verbose; requires C99 or later

There's also a hybrid form — mix positional and designated in the same initializer — but it's rarely worth the confusion. Pick one style and stick with it.

Complete C Program

Program: initialize a student struct and display it

#include <stdio.h>

struct student {
    char  name[50];
    int   roll;
    float marks[3];
};

int main(void) {
    /* Positional initialization at declaration */
    struct student s = {
        "Alice Johnson",
        101,
        {85.5, 90.0, 78.5}
    };

    /* Display the record */
    printf("Student Record\n");
    printf("--------------\n");
    printf("Name  : %s\n", s.name);
    printf("Roll  : %d\n", s.roll);
    printf("Marks : %.1f, %.1f, %.1f\n",
           s.marks[0], s.marks[1], s.marks[2]);

    return 0;
}
                                    

And here's the designated-initializer version (C99+), which is the safer style for real code:

Variant: designated initializers (C99)

#include <stdio.h>

struct student {
    char  name[50];
    int   roll;
    float marks[3];
};

int main(void) {
    struct student s = {
        .name  = "Alice Johnson",
        .roll  = 101,
        .marks = {85.5, 90.0, 78.5}
    };

    printf("Student Record\n");
    printf("--------------\n");
    printf("Name  : %s\n", s.name);
    printf("Roll  : %d\n", s.roll);
    printf("Marks : %.1f, %.1f, %.1f\n",
           s.marks[0], s.marks[1], s.marks[2]);

    return 0;
}
                                    

The first version is the traditional answer and works on any C compiler. The second is what modern C code uses, and it's worth learning because it's more maintainable — if someone later reorders the struct members, only the designated version continues to produce the correct result. For the assignment, either is acceptable; submit the positional one if your course is strict about C89, and the designated one if it uses C99 or later.

Program Output

Student Record
--------------
Name  : Alice Johnson
Roll  : 101
Marks : 85.5, 90.0, 78.5
                                

Try changing the initializer values — swap "Alice Johnson" for your own name, change the roll number to 202, and adjust the marks. The output should reflect your edits. Try the designated-initializer version with the members in a different order — it should still print the same output, because designated initializers match by name.

Step-by-Step Explanation

Let's walk through the positional version line by line, then look at the designated variant.

1. The struct definition

struct student { char name[50]; int roll; float marks[3]; }; declares the type. It's identical to assignment 1 — the definition doesn't change. What changes is how we create and populate the variable.

2. The initializer list

struct student s = {"Alice Johnson", 101, {85.5, 90.0, 78.5}}; — the three values are matched to name, roll, and marks in that order. The string literal "Alice Johnson" initializes the char name[50] array; the compiler copies the characters plus a null terminator. The int 101 initializes roll. The inner brace {85.5, 90.0, 78.5} initializes the three elements of marks. This is one statement, and it fully initializes every member.

3. What happens if you provide fewer values?

Suppose you write struct student s = {"Alice"};. The remaining members are zero-initialized: roll becomes 0, and marks[0..2] become 0.0. This is guaranteed by the C standard for static storage and by convention for automatic storage in most compilers — but strictly speaking, for automatic (local) variables, the standard says the remaining members are initialized "as if they had static storage duration," which means zero. So partial initialization is safe. The same applies to array members: {85.5} would set marks[0] = 85.5 and marks[1] = marks[2] = 0.0.

4. Printing each member

printf("%s", s.name) prints the name string. printf("%d", s.roll) prints the integer. printf("%.1f", s.marks[0]) prints a float with one decimal place. The field widths and labels ("Name :", "Roll :", "Marks :") are cosmetic — the compiler doesn't care — but they make the output readable, which matters for a program that's supposed to "display details".

5. Designated initializers in detail

The designated version uses the .member = value syntax. The compiler matches each designator to a member by name and initializes it. Unmentioned members are zero-initialized. You can write the designators in any order: {.roll = 101, .name = "Alice Johnson", .marks = {85.5, 90.0, 78.5}} produces the same struct. This is why designated initializers are robust to struct reordering — the values "travel with" their member names.

6. Why the inner braces are needed for the array

The marks member is itself an array, and in the positional form, the initializer for an array must itself be brace-enclosed: {85.5, 90.0, 78.5}. If you write {"Alice", 101, 85.5, 90.0, 78.5} without the inner braces, the compiler treats it as initializing name, roll, and then... stops, because a flat list can't initialize an array-of-3. The inner braces are the syntax's way of saying "these three values go into the array".

7. Designated vs positional — a real-world analogy

Think of positional initialization as filling out a form by field order: "first blank gets Alice, second blank gets 101, third blank gets..." If someone reorders the form, you'll fill in the wrong blanks. Designated initialization is filling out a form by label: "Name field: Alice, Roll field: 101, Marks field: ..." — order doesn't matter, and labels travel with the form. For 2-field structs, either works. For 10-field structs, designated is much safer. That's why C99 added it.

🎯 Remember this: use an initializer list at declaration for full initialization; positional values match members in order; designated values match members by name and are reorder-safe; missing values are zero-initialized; array members need inner braces in positional form.

Frequently Asked Questions

1. Can I use an initializer list after declaring the variable?

No — initializer lists are only valid at the point of declaration. Once the variable exists, you must assign each member individually (strcpy(s.name, "Alice"); s.roll = 101; and so on). The reason: an initializer list is part of the declaration statement, not a separate assignment. This is a frequent source of confusion for beginners coming from languages where constructors can run later.

2. What happens if I provide fewer values than members?

The remaining members are zero-initialized. So struct student s = {"Alice"}; gives name = "Alice", roll = 0, and marks = {0.0, 0.0, 0.0}. This is useful for defaults: initialize all members to zero with = {0} or = {0.0} (any single zero in the first position triggers full zero-initialization), then assign the ones you actually want.

3. What are designated initializers, and when were they added?

Designated initializers use the .member = value syntax to specify which member each value initializes, by name. They were added in C99 and are also available in C11 and later. They allow you to skip members, reorder the initializations, and — crucially — keep the code correct even if someone reorders the struct members. They're the modern C idiom for non-trivial structs.

4. Can I mix positional and designated initializers?

Yes, C11 allows it: struct student s = {"Alice", .roll = 101, .marks = {85.5, 90.0, 78.5}};. The first value goes to name (positional), then the rest are designated. It's legal but confusing — mixing styles makes the code harder to read and is worth avoiding unless you have a specific reason. Pick one style and stick to it.

5. What's the difference between struct student s = {"Alice"}; and struct student s; strcpy(s.name, "Alice");?

The first is initialization at declaration — the compiler creates the struct and fills in the specified members (the rest zero-initialized). The second is declaration followed by assignment — s is uninitialized until the strcpy call, and members like roll and marks remain uninitialized (garbage values) if you don't assign them. Initialization is safer; uninitialized structs are a common source of bugs.

6. Can I return a struct from a function and use it as an initializer?

Yes: struct student s = make_student(); initializes s from the returned struct. The returned struct is a temporary that gets copied into s (or initialized in place, in the return value optimization — an implementation detail). This is a common pattern for "factory" functions. For now, it's enough to know that the initializer list and function return are both valid ways to populate a struct at declaration.

💡 Tip: After this program, try changing the member order in the struct definition and see what the positional initializer produces. You'll find the values get misaligned — "Alice Johnson" still goes to name only if name is still first. Then try the same change with the designated initializer: it should still print the correct record, because designated values travel with their member names.

📖 Related Tutorials

  • 1. Create a Structure to Represent a Student
  • 3. Find the Average Marks of a Student Using a Structure
  • Structure Initialization in C
  • Accessing Structure Members
  • Defining a Structure
  • Array of Structures
  • Introduction to Structures in C
  • All 25 Structure Assignments

Previous Topic: -->> 1. Create a Structure to Represent a Student   ||   Next Topic: -->> 3. Find the Average Marks of a Student Using a Structure


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.