CJCoding With Joseph
15free / daySign inCreate account

Mastering C Textbook

Unlock Structs

What is a Struct?

A struct, short for structure, is a way to group several related variables into one unit. Each variable inside the struct is called a member. Unlike classes in object-oriented programming, all members of a struct are public, meaning they can be accessed and modified directly.


Basic Structure

Here is a basic struct. It is designed in a way so it can be used to hold player data for a game. This struct contains:

  • A char array for the player's name.

  • An int for health.

  • An int for attack power.

  • An int for shield value.

  • A double for the player's money.

#include <stdio.h>

struct Player {
    char name[50];  // Player's name
    int health;     // Health points
    int attack;     // Attack power
    int shield;     // Shield value
    double money;   // Money balance
};

int main() {}

📌 Note: Always define the struct above the main function so it can be used throughout the program


Using A Struct

Now, let's see how to declare a struct variable and assign values to it.

We will make a new player called p1 and assign some values. To access and modify the values inside the struct, we use the dot (.) operator.

#include <stdio.h>
#include <string.h> // Required for the strcpy() function

struct Player {
    char name[50];
    int health;
    int attack;
    int shield;
    double money;
};

int main() {
    // Declare a struct variable
    struct Player p1;

    // Assign values to struct members
    strcpy(p1.name, "Bob"); // use strcpy() instead of direct assignment (=) because strings are arrays in C.
    p1.health = 55;
    p1.attack = 100;
    p1.shield = 22;
    p1.money = 19.85;

    // Print struct values
    printf("Name: %s\n", p1.name);
    printf("Health: %d\n", p1.health);
    printf("Attack: %d\n", p1.attack);
    printf("Shield: %d\n", p1.shield);
    printf("Money: %.2f\n", p1.money);

    return 0;
}
Members only

Keep reading this lesson

You've reached the end of the free preview. Unlock the rest of this lesson plus 11 more lessons in Mastering C Textbook.

  • Unlimited coding questions
  • Unlimited access to all classroom material
  • Weekly live call for questions and guidance
  • 3,000 AI tutor tokens / month
  • Personal SQL database (3 MB)
  • Progress tracking

Cancel any time.