C Structs

What is a Struct?

A struct is a user-defined data type that groups related variables together.

It allows you to represent complex data like a person, student, or product.

Loading...
Output:

Creating a Struct Variable

After defining a struct, you can create variables of that type.

Loading...
Output:

Assigning Values

You can assign values to struct members using the dot (.) operator.

Loading...
Output:

Accessing Struct Members

Use the dot operator to access struct fields.

Loading...
Output:

Using typedef

typedef allows you to create a shorter name for a struct.

Loading...
Output:

Struct Initialization

You can initialize structs when creating them.

Loading...
Output:

Arrays of Structs

You can create arrays of structs to store multiple records.

Loading...
Output:

Structs and Functions

Structs can be passed to functions as arguments.

Loading...
Output:

Pointers to Structs

You can use pointers to access structs.

Use the arrow operator (->) instead of dot.

Loading...
Output:

Why Use Structs?

Structs allow you to organize related data into one unit.

  • Model real-world objects
  • Improve code readability
  • Work with complex data

Common Mistakes

Be careful with these:

  • Forgetting to include string.h for strcpy
  • Using dot instead of arrow for pointers
  • Not initializing struct fields

Practice

Create a struct Student with name and grade, then print its values.

Loading...
Output:

Need Help?