Structures in C programming

Structure Definitions

Structures are derived data types—they’re constructed using objects of other types.

    struct card {   char *face;   char *suit;};

Keyword struct introduces the structure definition. The identifier card is the structure tag, which names the structure definition and is used with struct to declare variables of the structure type—e.g., struct card.

Variables declared within the braces of the structure definition are the structure’s members.

    struct employee {
    char firstName[ 20 ]; // array members 
    char lastName[ 20 ];
    unsigned int age; // unsigned int member 
    char gender; // char member 
    double hourlySalary;
    }; // end struct employee

Defining Variables of Structure Types

Variables of a given structure type may also be declared by placing a comma-separated list of the variable names between the closing brace of the structure definition and the semicolon that ends the structure definition.

    struct card {
    char *face;
    char *suit;
    } aCard, deck[ 52 ], *cardPtr;

Operations That Can Be Performed on Structures

  • assigning structure variables to structure variables of the same type
  • taking the address (&) of a structure variable
  • accessing the members of a structure variable
  • using the sizeof operator to determine the size of a structure variable.

The program demonstrates the use of the structure member and structure pointer operators.

    // Structure member operator and 
    // structure pointer operator 
    #include <stdio.h>
    // card structure definition            
    struct card {                           
    char *face; // define pointer face   
    char *suit; // define pointer suit   
    }; // end structure card                

    int main( void ) { 
    struct card aCard; // define one struct card variable   
    struct card *cardPtr; // define a pointer to a struct card

    // place strings into aCard
    aCard.face = "Ace";   
    aCard.suit = "Spades";
    cardPtr = &aCard; // assign address of aCard to cardPtr

    printf( "%s%s%s\n%s%s%s\n%s%s%s\n", aCard.face, " of ", aCard.suit,
    cardPtr->face, " of ", cardPtr->suit,                           
      ( *cardPtr ).face, " of ", ( *cardPtr ).suit );                 
    } // end main

    Ace of Spades
    Ace of Spades
    Ace of Spades

Ads Right