Struct

​A struct is a heterogeneous aggregate data type

  • A “bundle” of different types of data rolled into a new type

    • struct StructName

  • Each instance of the struct is stored in a block of memory large enough to hold all the fields

struct Person {
    string name;
    double height; // inches
    int weight; // pounds
};

This declares the struct Person and defines it to have 3 members. It does not allocate any space. This is just the blueprint for instances of struct Person.

struct Declaration Notes

  • Must have ; after closing }

  • struct names commonly begin with uppercase letter

  • Multiple fields of same type can be in comma-separated list:

    • string name

      • address;

  • Use the dot (.) operator to refer to members of struct variables

  • Member variables can be used in any manner appropriate for their data type

// declaring and initializing in one line
struct Person andre = {“Andre the Giant”,
84+1./3, 520};

struct Person andre;
// initialize fields individually
andre.name = “Andre the Giant”;
andre.height = 84+1./3;
andre.weight = 520;

int weight = andre.weight; // get member value
andre.weight = 520; // set member value

/*
// compiler error
andre.age = 46; // no member named “age”
*/
typedef struct Person {
    string name;
    float height; // inches
    int weight; // pounds
} Person;

Renames “struct Person” to “Person”:

Person andre = {“Andre the Giant”, 84+1./3, 520}

Last updated

Was this helpful?