Home > Articles > Programming > C/C++

This chapter is from the book

3.2 Structures and Unions

Structures group members (data and functions) to create new data types. Structures encapsulate data members (usually different data types), much like functions encapsulate program statements. Unions are like structures, but data members overlay (share) memory, and unions may access members as different types. We use structures and unions in applications that need user-defined types, such as databases, windows, and graphics.

Structures

Structure definitions have several formats, all of which include data members and member functions. To show the formats for structure definitions, let's look at structure data members first. We'll examine structure member functions in the next section.

The first structure format appears frequently in header files.

 struct struct_name {
  Type data_member1;
  Type data_member2;
  Type data_memberN;
 };

The word struct_name is a new data type. Data members may be any type, including pointers, references, arrays, and other structures whose types do not have the same name as struct_name. The compiler does not allocate memory with this format because we define only a type and not a variable.

NOTE

Structure data members cannot have the same type name as their enclosing structure, but we can define pointers to the same structure type.

 struct node {        // structure type
  int data;         // data member
  node *fwd;        // pointer to struct type
  node *back;        // pointer to struct type
 };

Note how soon we drop the word struct from subsequent node definitions once we define it as a type.

The second structure format builds a structure from an existing structure type and includes an initialization list to initialize it.

 struct struct_name name = { init_list }; 

The keyword struct is optional when you define struct_name elsewhere. This format allocates memory for structure name, which is type struct_name. The brace-enclosed initialization list is optional.

The third structure format combines the first and second formats.

 struct struct_name {
  Type data_member1;
  Type data_member2;
  Type data_memberN;
 } name = { init_list };

This format allocates memory, and the keyword struct is necessary to define a structure type. You may omit struct_name in this format if you don't need to use it later on in another structure definition.

NOTE

Structure initializations require braces with init_list. Consider the following.

 struct X {      // structure definition
  int num;     // data member
 };

 X a = 12;      // illegal - no conversion
 X a = { 12 };    // legal - initializes data member

The first initialization without braces generates a compilation error because the compiler attempts to convert an integer 12 to a structure X type. The second initialization with braces is correct. Always use pairs of braces to properly initialize your structures.

Member Functions

C++ also allows function declarations (called member functions) inside structures.

 struct struct_name {
  Type member_function1(signature);
  Type member_function2(signature);
 };

Typically, member function names are distinct, but the name of a member function may be the same as another if their signatures differ. There is no size overhead for member functions inside structures (try sizeof() to convince yourself).

Member functions are essential in object-oriented programming because new data types combine functionality (member functions) with data (data members), all in a single unit. This concept lets you design objects with an implementation (how objects work) and an interface (how objects behave). We explore these important concepts in Chapter 4 with class definitions.

The dot (.) operator provides access to structure members.

 struct X {
  int num;           // data member
  int f();           // member function
 };

 X a = { 12 };          // initialize data member
 cout << a.num << endl;      // data member, displays 12
 cout << a.f() << endl;      // calls member function

Structure Pointers

Pointers may address structures. The formats are

 struct struct_name {
  Type data_member;
  Type member_function(signature);
 } *pname = { init_list };

 struct struct_name *pname = { init_list };

The brace-enclosed init_list is optional and must contain a pointer expression whose type matches or converts to struct_name. If you initialize structure pointers, the braces surrounding init_list are not necessary. The word struct_name is optional in the first format, and the keyword struct is optional in the second format when you define struct_name elsewhere.

Here are the two formats to access structure members.

 struct_name_variable.member_name   // structure
 struct_name_pointer->member_name   // structure pointer

A structure variable name must appear to the left of the . (dot) operator and a structure pointer name must appear to the left of the -> (arrow) operator. Here are some examples of these operators with structure type block.

 struct block {            // structure type
  int buf[80];           // data member
  char *pheap;           // data member
  void header(const char *);    // member function
 };

 block data = { {1,2,3}, "basic" };  // structure variable
 block *ps = &data;          // structure pointer

 data.pheap++;            // increment data member
 data.header("magic");        // call member function
 ps->pheap++;             // increment data member
 ps->header("magic");         // call member function
 ps.pheap++;             // illegal, ps is a pointer
 data->header("magic");        // illegal, data is a structure

The inner braces in the initialization list for data initialize only the first three integers of the buf data member array (the remaining elements are zero). The precedence of . and -> is high; hence, no parentheses are necessary to combine them with a ++ operator when we increment pheap.

Be aware that memory allocation for structures does maintain the order of its data members in structure definitions. Structures, therefore, may contain "holes" due to machine word alignment (buf[79] in place of buf[80], for example).

Arrays with Structures

Arrays of structures and arrays of structure pointers are also possible. Two groups of formats exist. Here is the first one.

 struct struct_name name[size] = { init_list };
 struct struct_name name[size1][size2][sizeN] = { init_list };

 struct struct_name *pname[size] = { init_list };
 struct struct_name *pname[size1][size2][sizeN] = { init_list };

The keyword struct is optional when you define struct_name elsewhere, and the rules for size are the same as the rules for arrays of built-in types (see "Arrays" on page 35). The optional brace-enclosed init_list initializes a data member in each array element. With arrays of structure pointers (pname), init_list must have pointer expressions that match or convert to struct_name. When you initialize arrays of structures or arrays of structure pointers, you must include braces with init_list.

The second group of formats define a structure type and follow the same rules as above. The keyword struct must appear in both formats, but struct_name is optional.

 struct struct_name {
  Type data_member;
  Type member_function(signature);
 } name[size1][size2][sizeN] = { init_list };

 struct struct_name {
  Type data_member;
  Type member_function(signature);
 } *pname[size1][size2][sizeN] = { init_list };

Here are several examples of structure arrays.

 struct block {           // structure type
  int buf[80];          // data member
  char *pheap;          // data member
  void header(const char *);   // member function
 };

 block dbase[2] = {         // array of 2 structures
  { {1,2,3}, "one" },       // initialize first element
  { {4,5,6}, "two" }       // initialize second element
 };
 block *pb[2];           // array of 2 pointers to block

 dbase[1].pheap++;         // increment data member
 dbase[1].buf[0] = 'x';      // assign to data member
 dbase[1].header("magic");     // call member function

 pb[1] = &dbase[1];        // pb[1] points to dbase[1]
 pb[1]->pheap++;          // increment data member
 pb[1]->buf[0] = 'x';       // assign to data member
 pb[1]->header("magic");      // call member function

NOTE

In the above example, we use an outer pair of braces on separate lines to initialize each member of the dbase structure array. Braces surrounding individual structure array elements make their initializations readable and easy to modify. Remember to use at least one pair of braces.

Nested Structures

Structure definitions that appear inside other structure definitions are nested structures. Here is an example.

 struct team {
  struct address {          // nested structure
    char location[80];        // team location
    int zipcode;           // team zip code
  };
  char name[20];           // name of team
  address sponsor;          // sponsor's address
  address home_field;         // home field address
 };

Nested structures encapsulate structure definitions and make them an integral part of an enclosing structure definition. Use the . or -> operators in succession to access the member you want from a nested structure.

 team soccer = { "bears", {"123 Main", 30302}, {"8 Elm", 32240} };
 team *ps = &soccer;             // structure pointer

 cout << soccer.name << endl;         // displays "bears"
 cout << soccer.sponsor.zipcode << endl;   // displays 30302
 cout << ps->home_field.zipcode << endl;   // displays 32240

The first cout statement uses a . operator to display the team's name. Two . operators are necessary to display the zip code of the team's sponsor in the second cout statement. The third cout statement uses -> with structure pointer ps and . with structure data member home_field to display the team's home field zip code.

NOTE

Nested structures can use the same name as their enclosing structure names if they nest, too. Consider the following.

 struct X {             // outer X
  struct Y {            // Y nested in outer X
    struct X {          // inner X nested in Y
     int i;           // member of inner X
    };
    X mystuff;          // member of Y
    int j;            // member of Y
  };
  Y stuff;             // member of outer X
  int k;              // member of outer X
 };

A structure Y nests inside outer structure X. Structure Y also nests an inner structure X, which is legal because its name is distinct from its immediately enclosing structure name (Y). Sometimes name collisions do occur when you piece together existing structures to form new ones, so be aware of this rule.

Typedefs with Structures

Chapter 2 introduces typedefs as synonyms for built-in types (see "Typedefs" on page 43). Typedefs also apply to structures and help make structure definitions more readable. Consider the structure definitions from the previous section.

 struct node {
  int data;
  node *fwd;
  node *back;
 };
 node element;
 node *p = &element;

Here's how we can simplify this code with the following typedef.

 typedef struct node *Pnode;

 struct node {
  int data;
  Pnode fwd;
  Pnode back;
 } ;
 node element;
 Pnode p = &element;

Pnode is a synonym for struct node *. This typedef eliminates the pointer notation from our original code and makes it more readable.

NOTE

Create typdef names with uppercase first letters for better readability. Place typedef statements and structure definitions in header (.h) files and #include them where necessary. Remember that typedefs are not new types; they are just synonyms for existing ones. Typedefs, therefore, are not type safe.

Structure Copy and Assignment

Sometimes you want to save a structure temporarily or initialize a new structure from another one of the same type. The following statements attempt to copy the data members of one structure into another structure of the same type.

 struct value {         // structure definition
  double x;
  char name[10];
 } a = { 5.6, "start" };    // initialize members of struct a

 value b;            // structure b of same type
 b.x = a.x           // legal - copy doubles
 b.name = a.name;        // illegal - not lvalues

Separate data member assignments are not only tedious for structures with a large number of members, but assignments fail with array members (array names are not lvalues). Fortunately, there is an easier way.

 value b = a;         // structure copy
 value c;
 c = a;            // structure assignment

With structures of the same type, you may copy an existing structure to a new one or assign one structure to another. The compiler copies each member of one structure into the other (even array members!).

Remember that references to structures do not perform structure copies.

 value f;         // structure
 value & e = f;      // reference to a structure

The reference e is only an alias for structure f.

NOTE

Use structure copy and assignment statements. For built-in types (char, int, float, etc.), most compilers generate in assembly code block move instructions, which move data in memory without loops or counters. Thus, structure copy and assignment are efficient and convenient.

Unions

Unions have the same formats and operators as structures. Unlike structures, which reserve separate chunks of memory for each data member, unions allocate only enough memory to accommodate the largest data member. On 16-bit and 32-bit machines, for example, the definition

 union jack {
  long number;
  char chbuf[4];
 } chunk;

allocates only four bytes of memory. Variable chunk.number is a long, and chunk.chbuf[2] (for example) is a char, both within the same memory area. Figure 3.3 shows the memory layout for chunk.

Figure 3.3Figure 3.3. Memory layout of a union

You may create pointers to unions and initialize unions with an lvalue of the same data type as the union's first data member. Member functions are legal inside union definitions, but data members with constructors are not (see "Constructors" on page 181). Union assignment works just like structure assignment. Maintaining data integrity for union members is the programmer's responsibility.

C++ also has anonymous unions. An anonymous union allocates memory for its largest data member but doesn't create a type name (hence the name "anonymous"). Here's the format.

 union {
  Type data_member1;
  Type data_member2;
  Type data_memberN;
 };

A program that declares an anonymous union may access data members directly (without a . or ->). Member functions are illegal inside anonymous union definitions.

To demonstrate anonymous unions, Listing 3.7 employs another version of itoh(), which converts short variables to hexadecimal characters for display.

Listing 3.7 Integer-to-hexadecimal conversion, using anonymous union

 void itoh(unsigned short n) {
  union {               // anonymous union
    unsigned short num;
    unsigned char s[sizeof(short)];
  };
  const char *hex = "0123456789abcdef";
  num = n;              // store number as a short

  cout << hex[s[1] >> 4];       // first byte - high nibble
  cout << hex[s[1] & 15];       // first byte - low nibble

  cout << hex[s[0] >> 4];       // second byte - high nibble
  cout << hex[s[0] & 15];       // second byte - low nibble
 }

An anonymous union creates two bytes (16 bits) of memory for itoh() to access. The statement num = n stores the number we pass to itoh() into memory as a short, and the cout statements access the same bytes of memory as characters. We use a 4-bit right shift (>> 4) to access the high nibble (4 bits) and a 4-bit mask (& 15) to access the low nibble. Both operations yield a 4-bit result between 0 and 15, which we use as an index with pointer hex to convert the result to ASCII characters ('0' to 'f'). The memory that our anonymous union creates is available only inside itoh().

Why use this technique? First, this version of itoh() executes fast. Unlike other versions, there are no recursive calls, loops, or multiply or divide operators. Second, on some machines, the assembly code from this function may be smaller in size than other versions. In time-critical code or with programs that have memory constraints, this version of itoh() may be preferable to others.

NOTE

Unions are not always portable, due to the way different processors store bytes in memory. Our version of itoh(), for instance, runs correctly on IntelÆ processors, but displays the bytes in reverse order on SPARCÆ-based workstations. The following preprocessor statements declare and initialize a const integer that identifies the machine we are using.

 #ifdef SPARC
 const int byte = 0;         // SPARC-based
 #else
 const int byte = 1;         // Intel
 #endif

Inside itoh(), we modify the cout statements as follows.

 cout << hex[s[byte] >> 4];      // first byte - high nibble
 cout << hex[s[byte] & 15];      // first byte - low nibble

 cout << hex[s[!byte] >> 4];     // second byte - high nibble
 cout << hex[s[!byte] & 15];     // second byte - low nibble
 

You may extend these preprocessor statements to handle other machines as well. This approach lets you maintain one version of itoh() that's portable across different machines.

Bitfields

When hardware assigns special meanings to bits in memory, bitfields are often easier to work with than bit masks and shift operators. The following dbyte structure definition, for instance, defines four bitfield data members, all in the same integer word.

 struct dbyte {
  unsigned int flag  : 1;     // one bit
  unsigned int mode  : 2;     // two bits
  unsigned int    : 1;     // unused bit
  unsigned int type  : 4;     // four bits
 };

A bitfield is any integral type (signed and unsigned char, short, int, long, or an enumerated type). The number following the colon separator must be a constant expression and specifies the number of bits for the bitfield. Member flag, for example, is one bit, whereas mode and type are two bits and four bits, respectively. An unnamed bitfield (the third member in dbyte) is useful for padding bits within other named bitfields. A zero following the colon separator aligns the following bitfield on a machine-specific addressable boundary. The address operator (&) and references and pointers are illegal with bitfields. The keyword static (page 125) is also illegal with bitfields.

Here's an example on a machine with 16-bit word sizes.

 dbyte v = { 0 };            // create word with bitfields
 v.flag = 1;               // 0000 0000 0000 0001
 v.mode = 3;               // 0000 0000 0000 0111
 v.type = 9;               // 0000 0000 1001 0111

Each assignment statement sets the appropriate bits within a bitfield, which we show with italics inside the comments. The following reinterpret cast converts the address of v to an integer pointer before we dereference and display the integer result. Here's the output.

 int n = *reinterpret_cast<int *>(&v);
 cout << hex << n << endl;      // displays 97 (hex)

NOTE

The compiler packs adjacent bits within the same integer in the order that the bitfield members appear inside a structure or class definition. Be aware that this ordering is machine dependent, however. On another 16-bit machine, for example, the above example displays a different result.

 cout << hex << n << endl;   // displays e900 (hex) 

The hexadecimal output displays the bits in reverse order because this machine packs bits right-to-left. Use bitfields carefully within your designs and remember that bitfields do not always conserve memory. Extracting a 2-bit bitfield from an integer word, in fact, may take longer than accessing an 8-bit character on some machines.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020