Lesson 13

ArtyArty
2 min read

Structures

  • Also known as

    • Aggregates

    • Collection of variables under on name

    • May contain variables of different data types

    • Derived data types

  • Commonly used to store records in files

  • Getting member information

    • from an instance uses the dot operator (.)

    • from a pointer uses the arrow operator (->)

  • Pointers and structures are used to form data structures in C (Linked list, stacks, queues, etc)

  • Declaring a new instance requires the struct keyword and the name of the instance (eg. struct card {<members' definition>}).

  • instantiating (Tag definition) requires is both the struct keyword and the name of the struct (eg. struct card h9 = {<values>};).

  • A structure may have a pointer to itself, however, an instance to itself will result in syntax error

Structure Type

  • typedef provides a mechanism for creating synonyms.

  • typedef is often used to define a structure type, so a structure tag is not required.

Structure definition, initialization & basic usage example

/*
$ gcc -o basics ./basics.c && ./basics
data from instance : Nine Hearts
data from pointer  : Nine Hearts
*/

#include <stdio.h>

int main(int argc, char *argv[]){
    // declaration
    struct card {
        char *face;
        char *suit;
    };

    // declaration & instantiation of instance
    // and a declaration of pointer to a structure
    struct card h9 = {"Nine", "Hearts"}, *card_ptr;

    // instantiation of struct pointer
    card_ptr = &h9;

    // getting member information using dot operator
    printf("data from instance : %s %s\n", h9.face, h9.suit);
    // getting member information using arrow operator
    printf("data from pointer  : %s %s\n", card_ptr->face, card_ptr->suit);

    return 0;
}

Example of a pointer to itself

/*
$ gcc -o self-pointer ./self-pointer.c && ./self-pointer
data from instance : Nine Hearts
data from pointer  : Nine Hearts
*/

#include <stdio.h>

int main(int argc, char *argv[]){
    struct person {
        char *full_name;
        // error: field has incomplete type 'struct person'
        // struct person mentor2;
        struct person *mentor;
    };

    struct person jane = {"Jane Doe", 0};
    struct person john = {"John Doe", &jane};

    printf("basic data access\n");
    printf("  john   : %s\n", john.full_name);
    printf("  mentor : %s\n", john.mentor->full_name);

    printf("converting mentor to instance before data accessing\n");
    printf("  mentor : %s\n", (*(john).mentor).full_name);

    return 0;
}

Example of untagged struct type

typedef struct {
    char *full_name;
}  person;
0
Subscribe to my newsletter

Read articles from Arty directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Arty
Arty