How to Access Elements of a Structure in C

Embedded C for microcontrollers



In this article, we go over how to access elements of a structure in C.

A structure is a data element in C that can be composed of elements of different data types. It is used to create user-defined data types and allows us to combine data of different types.

As an example, let's go over creating a data structure representing a house.

We will have data elements, including the house size, house price, number of bedrooms, number of bathrooms, and whether the house has a pool or not.

These data elements will be of different types. The house size will be of a 32-bit integer. The house price will be of a 32-bit integer size. The number of bedrooms will be an 8-bit integer. The number of bathrooms will be an 8-bit integer. The presence of a pool will be a boolean variable for true or false.

So below we create a structure and initialize it with the example above. We then access the elements by using the name of the struct element followed by a period and the individual data element.



So we create a structure data type called House.

This is composed of several elements including housePrice (uint32_t), houseSize (uint16_t), houseBedrooms (uint8_t), houseBathrooms, and pool (bool).

The struct data type is normally declared outside of the main function and may even be placed in the header file.

We then have our main function.

This is the place, however, where we initialize the struct data type.

We create a struct element that is of type House; we name it redHouse.

The house size is 1200 (square feet), the house price is $250000, the number of bedroom is 2, the number of bathroom is 2, and there is no pool, so we set the value equal to false.

We then output the redHouse data elements using the printf statements.

How to access an element of a struct object, we reference the name of the struct object followed by a period followed by the individual data element.

So to reference the house price, the reference is, redHouse.housePrice

To reference the house size, the reference is, redHouse.houseSize

To reference the number of house bedrooms, the reference is, redHouse.houseBedrooms

To reference the number of house bathrooms, the reference is, redHouse.houseBathrooms

To reference whether the house has a pool or not, the reference is, redHouse.pool

The output of this program is shown below.



So this is how we can access and display elements of a structure in C.

Related Resources

How to Set Bits of a Number in C

How to Clear Bits of a Number in C



HTML Comment Box is loading comments...