Your browser doesn't support JavaScript Structures – Windows Programming

Structures

A structure is a user-defined data type that groups related variables under a single name. It allows variables of different data types to be combined into one entity, making related information easier to organise and manipulate within a program.

Each variable declared within a structure is called a member of that structure. Structure members can have different data types, such as int, char, and float.

Defining and Declaring Structures

The struct keyword is used to define a structure type. It is followed by a structure tag, which names the type. An opening curly brace { is followed by the declarations of the structure’s members, and a closing curly brace } completes the definition.

Once the structure type has been defined, variables of that type can be declared either as part of the structure definition or separately afterwards.

struct account
{
    int accountno;
    char *lastname;
    char *firstname;
    int age;
    unsigned int telephone;
} user1;  // Declares user1 as a structure variable

struct account user2, user3;  // Declares two more structure variables

In this example:

  • struct account defines a structure type named account.
  • accountno, lastname, firstname, age and telephone are the structure’s members.
  • user1 is declared as a structure variable at the end of the definition.
  • user2 and user3 are declared separately as variables of type struct account.

Each structure variable has its own set of members. For example, user1.accountno and user2.accountno refer to the account numbers belonging to two different structure variables.

Note: lastname and firstname are declared as char *, meaning they are pointers to characters. They do not automatically provide storage for text. If you want each member to contain its own character array, you could instead declare them as char lastname[50]; and char firstname[50];.

Note: In C++, the struct keyword is optional before the variable declaration. In C, it is compulsory.

Accessing Members of a Structure

Structure members are accessed using the dot operator (.) between the structure variable name and the member name.

For example, to set the age member of the structure variable user1 to 21, use:

user1.age = 21;

The dot operator can also be used to retrieve a member’s value. For example:

printf("%d\n", user1.age);

This statement prints the value stored in the age member of user1.

Initialising Structures

When a structure variable is initialised, the initialiser usually consists of a brace-enclosed, comma-separated list of values. These values correspond to the structure members in the order in which they are declared.

For example, using the previously defined struct account:

struct account user4 = {123, "john", "doe", 12, 123456789};struct account user4 = {123, "john", "doe", 12, 123456789};

The values are assigned as follows:

  • accountno is initialised to 123.
  • lastname points to the string literal “john”.
  • firstname points to the string literal “doe”.
  • age is initialised to 12.
  • telephone is initialised to 123456789.

Note: The string literals are not copied into character arrays here. The members lastname and firstname are pointers to characters, so they point to the respective string literals.

Structure members cannot normally be given individual initial values inside the structure type definition. Instead, values are supplied when a structure variable is initialised, or assigned to its members later. A structure type definition describes the layout of the data; declaring a structure variable creates an object that has storage for its members.

Designated Initialisation

Designated initialisation allows specific structure members to be initialised by name, rather than relying entirely on their declaration order. This feature was introduced in the C99 standard.

A designated initialiser uses a dot followed by the member name and an equals sign, as shown below:

struct account user5 = {
    .lastname = "jill",
    .firstname = "doe",
    .accountno = 123,
    .age = 21,
    .telephone = 123456789
};

The initialisers can appear in any order because each value is explicitly associated with a member name.

If subsequent values are provided without designators, they initialise the members following the last designated member in declaration order. Care is therefore needed when mixing designated and positional initialisers.

For clarity, using a designator for every member, as in the example above, makes the initialisation easier to read and maintain.

Arrays of Structures

An array of structures is a sequential collection of structures. After the structure has been defined, an array of structures is declared as follows-

struct userdetails list[100];

The above statement declares an array named list that contains 100 elements. Each element is a structure of type userdetails and is identified by subscript. The structure data can be manipulated by specifying the appropriate index value of the array. Like a standard Array, an array of structures can be initialised at compile time.

Individual structure members can be accessed by specifying the array index followed by the dot (.) operator. For example:

list[0].age = 25;
list[1].age = 30;

These statements assign the value 25 to the age member of the first structure and 30 to the age member of the second structure.

Like ordinary arrays, arrays of structures can be initialised when they are declared. For example:

struct userdetails list[2] = {
    {101, "John", 25},
    {102, "Jill", 30}
};

Each set of values inside braces initialises one structure, with the values corresponding to the members in the order in which they were declared.

Structures and Pointers

Structures can be accessed and manipulated by pointers. Pointers to structures can be declared by preceding the variable name with an asterisk. The individual member variables are accessed using the operator instead of the .(dot) operator

#include <stdio.h>
int main(void) 
{
struct account{
unsigned int accountno;
char *firstname;
char *lastname;
unsigned int telephone;
} user1={123,"joe","blogs",123456789};//structure variable user1 defined and initiated
struct account *ptrStr;//create pointer of type struct account
ptrStr = &user1;//set pointer to address of user1

printf("%d %s %s %d", ptrStr->accountno,ptrStr->firstname, ptrStr->lastname,ptrStr->telephone);//access elements using ->
return 0;
}

Explanation

  • struct account defines the structure type and its members.
  • user1 is a structure variable initialised with an account number, first name, last name and telephone number.
  • struct account *ptrStr; declares a pointer that can hold the address of a struct account variable.
  • ptrStr = &user1; assigns the address of user1 to the pointer. The & operator obtains the variable’s address.
  • ptrStr->accountno accesses the accountno member through the pointer. The same syntax is used for the other members.

The arrow operator is shorthand for dereferencing a structure pointer and then accessing a member. For example:

ptrStr->accountno

is equivalent to:

(*ptrStr).accountno

The parentheses are necessary because the dot operator has higher precedence than the dereference operator (*).

Output:

123 joe blogs 123456789

Note: %u is the appropriate printf format specifier for an unsigned int.

Passing Structures as Arguments to Functions

An entire structure can be passed to a function as an argument. In C, a structure can be passed by value, which passes a copy of the structure, or by reference, which is achieved by passing a pointer to the structure.

Passing a structure parameter by value – To Pass a structure parameter by value declare the function to use the type of structure you’ve created. When the function is called, a copy of the structure is created and used by the function. Any modification to the structure made inside of the function won’t the effect original.

#include <stdio.h>

struct account {
    unsigned int accountno;
    char *firstname;
    char *lastname;
    unsigned int telephone;
};

void function1(struct account user1copy)
{
    printf("%u\n", user1copy.accountno);
    printf("%s\n", user1copy.firstname);
    printf("%s\n", user1copy.lastname);
    printf("%u\n", user1copy.telephone);
}

int main(void)
{
    struct account user1 = {123, "joe", "blogs", 123456789};

    function1(user1);

    return 0;
}

In this example, function1() receives a copy of user1, named user1copy. The function can access the copied structure’s members using the dot (.) operator.

Passing a structure parameter by reference – To be able to change the structure inside of our function, then it must be passed by reference. Any changes made to the structure members are reflected in the original structure. This is because pointers deal directly with the data stored in the memory.

#include <stdio.h>

struct account {
    unsigned int accountno;
    char *firstname;
    char *lastname;
    unsigned int telephone;
};

void function2(struct account *user1ptr)
{
    user1ptr->accountno = 456;
}

int main(void)
{
    struct account user1 = {123, "joe", "blogs", 123456789};

    function2(&user1);

    printf("%u\n", user1.accountno);

    return 0;
}

Output: 456

In this example:

  • struct account *user1ptr declares a pointer parameter.
  • function2(&user1) passes the address of the original structure using the address-of (&) operator.
  • user1ptr->accountno = 456; changes the original structure’s accountno member using the arrow (->) operator.

Summary

  • Pass by value: The function receives a copy of the structure. Changes to its members do not change the original structure.
  • Pass by reference using a pointer: The function receives the structure’s address and can modify the original structure’s members.

Note that passing a structure by value copies its members. If a member is a pointer, the pointer value is copied, not the data it points to.

Structures Within Structures

In C, one structure can contain another structure as a member. This is known as a nested structure. The inner structure can be declared directly inside the outer structure, or the two structure types can be declared separately.

#include <stdio.h>
int main(void) {
struct outer {//declare outer stucture
int member1;
int member2;
int member3;

struct embedded{//declare inner structure
int member_1;
int member_2;
int member_3;
} embeddedvar;//declare inner struct variable
} outervar={3,4,5,{1,2,3}};//declare outer stuct variable and initialise outer values and then inner values

// structure embedded
printf("%d", outervar.embeddedvar.member_1);//output embedded member_1
printf("%d", outervar.member1);//output member1
return 0;
}

In this example, the inner structure is declared separately from the outer structure. The outer structure then contains a member of the inner structure’s type.

#include <stdio.h>
int main(void) {
struct embedded
{
int member_1;
int member_2;
int member_3;
};

struct outer
{
struct embedded embeddedvar; //declare embadded variable
int member1;
int member2;
int member3;
} outervar={{1,2,3},3,4,5};

printf("%d", outervar.embeddedvar.member_1);
printf("%d", outervar.member1);
return 0;
}

Output: