Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A clear, simple explanation of what a struct is in C

Tags:

c

struct

I already have somewhat of an idea, but I thought it would be good to get some input from the wonderful people here at sof.

Please let me know if my question is too broad or vague.

like image 507
Eric Brotto Avatar asked Dec 03 '22 09:12

Eric Brotto


1 Answers

The question is a bit broad, but...

A struct is an aggregate or composite data type, used for representing entities that are described by multiple attributes of potentially different types. Some examples:

  • A point in 3-D space, represented by 3 real-valued coordinates x, y, and z;
  • A mailing address, represented by a street name, house or apartment number, city, state, ZIP code;
  • A line item in an invoice, represented by a part name or number, unit cost, quantity, and subtotal;
  • A node in a tree, represented by a key, data value, left child, and right child;

etc., etc., etc.

Let's look at the mailing address as a concrete example. We could define our mailing address type as follows:

struct Address {
  char *streetName; 
  int buildingNumber;  // House, apt building, office building, etc.    
  char *aptNumber;     // Handles apt and suite #s like K103, B-2, etc.
  char *city;
  char state[3];
  int zip;
};

We'd create an instance of that struct like so:

struct Address newAddress;

and a pointer to that instance as:

struct Address *addrPtr = &newAddress;

and access each of its fields using either the . or -> operator depending on whether we're dealing with a struct instance or a pointer to a struct:

newAddress.streetName = strdup("Elm");
addrPtr->buildingNumber = 100;
...

Another way to look at structs is something like a database record composed of multiple fields.

like image 191
John Bode Avatar answered Dec 22 '22 00:12

John Bode