Eric Brotto
Eric Brotto

Reputation: 54251

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

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.

Upvotes: 4

Views: 3656

Answers (4)

John Bode
John Bode

Reputation: 123458

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.

Upvotes: 9

Christoph
Christoph

Reputation: 169563

Perhaps not the most simple explanation, but for completeness, here's what the standard has to say about structures (C99 6.2.5 §20):

A structure type describes a sequentially allocated nonempty set of member objects (and, in certain circumstances, an incomplete array), each of which has an optionally specified name and possibly distinct type.

Upvotes: 2

Christoffer
Christoffer

Reputation: 12910

It's a custom memory layout with human-readable aliases for the offsets within the memory area.

Upvotes: 6

Mahesh
Mahesh

Reputation: 34625

From MSDN -

A structure type is a user-defined composite type. It is composed of fields or members that can have different types.

Upvotes: 0

Related Questions