Log in / create account | Login with OpenID
DocForge
Programmer's Wiki

Struct

From DocForge

This page is a stub. It's lacking in details and can use your help. Please contribute your knowledge to this page.

A struct is a C and C++ concept to group several typed fields inside a single, new, type. This new type can subsequently be used alongside any other types. This can be convenient for several reasons:

  • When passing arguments to a function-call, only a single entity has to be transferred, resulting in better code legibility.
  • When returning a value from a function-call, multiple values, all captured inside the struct, can be returned instead of just one.

To the programmer, a struct acts like an in-memory record. To the compiler, a struct is just a specification of size, and a member of a struct is just an offset in memory relative to where the storage of the struct starts. The offset is usually the result of the addition of the size of the fields before it. Since a struct gives the programmer the possiblity to create types with odd, non-alignable sizes however, it is not specified that arrays of structs won't be 'padded' to align more properly.

The following code contains the declaration of a struct and a function which uses the struct both as an argument type, and as its return type:

struct foo {
  int bar;
  char foobar;
};
 
struct foo somefunction(struct foo);

The fields of this here struct would be addressed to read and written as follows, with 'record-dot-member' notation:

struct foo somefunction(struct foo foo_me) {
  int my_bar = foo_me.bar;
  char my_foobar = foo_me.foobar;
  foo_me.bar = 12345;
  foo_me.foobar = 'A';
  return foo_me;
}

Theoretically (but why would one ?!), one could extract the fields from the struct as follows:

struct foo somefunction(struct foo foo_me) {
  char* ptr = (char*)&foo_me;
  int my_bar = *((int*)ptr);
  char my_foobar = ptr[sizeof(int)];
  return foo_me;
}

Also note that, in 32-bit systems, the natural integer size will be four bytes long, and that therefore, the size of this struct will be five bytes. An array of struct foo cannot be assumed to be arraysize * 5 bytes long, and its individual elements cannot be assumed to be laid out at positions index * 5.