C - Structure Understanding struct

Introduction

struct is a C language keyword that creates a structure.

struct record 
{ 
      char name[32]; 
      int age; 
      float debt; 
}

Within the curly brackets live the structure's members.

The record structure type contains three member variables: a string name, an int named age, and a float value, debt.

To use the structure, you must declare a structure variable of the structure type you created. For instance:

struct record human;

This line declares a new variable of the record structure type. The new variable is named human.

Structure variables can be declared when you define the structure itself. For example:

struct record 
{ 
      char name[32]; 
      int age; 
      float debt; 
} human; 

These statements define the record structure and declare a record structure variable, human.

Multiple variables of that structure type can also be created:

struct record 
{ 
      char name[32]; 
      int age; 
      float debt; 
} r1, r2, 43, r4; 

Four record structure variables are created in this example. Every variable has access to the three members defined in the structure.

To access members in a structure variable, you use a period, which is the member operator.

It connects the structure variable name with a member name. For example:

printf("Victim: %s\n",r4.name); 
r2.age = 32; 

The following code shows how to use a struct.

Demo

#include <stdio.h>

int main()// www  .j av  a 2s . c o  m
{
    struct player
    {
        char name[32];
        int highscore;
        float hours;
    };
    struct player xbox;

    printf("Enter the player's name: ");
    scanf("%s",xbox.name);
    printf("Enter their high score: ");
    scanf("%d",&xbox.highscore);
    printf("Enter the hours played: ");
    scanf("%f",&xbox.hours);

    printf("Player %s has a high score of %d\n",xbox.name,xbox.highscore);
    printf("Player %s has played for %.2f hours\n",xbox.name,xbox.hours);

    return(0);
}

Result

Related Topic