A Simple Guide to Using Structures in C

A struct (or structure) is a mixed data type in C. You can use it to store variables in different types.

The struct type is comparable to classes in object-oriented programming. Sometimes you may need to assign values to objects with the same properties. Instead of creating multiple variables for these objects in your C program, you can define them in a struct.

Creating a Struct

To define a structure, use the keyword struct, followed by the structure name. Inside the structure, you can specify variables of different types:

struct Car{
char name[45];
int wheels;
double cost;
} ;

You can define several instances of Car by adding those instance declarations after the right brace in your struct declaration:

struct Car{
/* variables */
} Car1, Car2, Car3;

You can also nest a structure inside a structure. See the example below:

struct address {
int area_code;
char street_name[45];
};
struct Person {
char name[60];
float height;
struct address Persons_location;
};

Related: C Programming Tips You Must Learn to Get Started

Operations on Struct Types

Initialization

There are three ways in which you can initialize the elements of a struct.

You can insert the comma-separated values in {} brackets & then assign them to the structure. You should note that the values must be in the same order that you declared the variables.

struct Car Car1 = {"Truck", 10, 65000};

Related: A Beginner’s Guide to the Standard Template Library in C++

You can also assign the values without minding the order in which you declared them. See the example below.

struct Car Car2 = {
.cost = 45000,
.name = "Truck",
.wheels = 8
};

The third way to initialize your struct is to assign it an existing structure of the same type.

struct Car Car3 = Car1;

Accessing Struct Elements

To access the value stored in a structure element, use the dot operator.

/* the syntax is:
structName.elementName */
int y = Car1.wheels;

A Look at Object-Oriented Programming

As mentioned at the beginning, struct is comparable to using classes in object-oriented programming (OOP). Classes are simpler to use and enable code reuse.

For this reason and many others, C++ was introduced. C++ is the object-oriented version of C. Next on your reading list should be understanding the concepts in OOP.

Source: makeuseof.com

Related posts

Connections #329: Today’s Answer and Clues (Sunday, May 5, 2024)

PC Fans Running at Full Throttle? 6 Fixes

The 5 Best Free Driver Updaters for Windows