C Structure

C arrays allow defining variables that can store data items of the same type,Structureand are another user-defined data type available in C programming, which allows you to store data items of different types.

Data members in a structure can be basic data types (such as int, float, char, etc.), or other structure types, pointer types, and so on.

Structures are used to represent a record. Suppose you want to track the dynamics of books in a library; you may need to track the following attributes for each book:

  • Title
  • Author
  • Subject
  • Book ID

Define structure

The structure definition consists of the keywordstructand the structure name. The structure name can be defined as needed.

The struct statement defines a new data type containing multiple members. The format of the struct statement is as follows:

struct tag {
    member-list
    member-list
    member-list  
    ...
} variable-list ;

tagIs a struct tag.

member-listis a standard variable definition, such asint i;orfloat f;, or other valid variable definitions.

variable-listStructure variables, defined at the end of the structure, before the final semicolon, you can specify one or more structure variables. The following is the way to declare a Book structure:

struct Books
{
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
} book;  

In general,tag、member-list、variable-listAt least 2 of these 3 parts must appear. The following is an example:

// This declaration declares a structure with 3 members, namely integer a, character b, and double c
// It also declares the structure variable s1
// This structure does not specify its tag
struct
{
    int a;
    char b;
    double c;
} s1;

// This declaration declares a structure with 3 members, namely integer a, character b, and double c
// The structure's tag is named SIMPLE, and no variable is declared
struct SIMPLE
{
    int a;
    char b;
    double c;
};
// Using the structure with the SIMPLE tag, additional variables t1, t2, t3 are declared
struct SIMPLE t1, t2[20], *t3;

// You can also use typedef to create a new type
typedef struct
{
    int a;
    char b;
    double c;
} Simple2;
// Now Simple2 can be used as a type to declare new structure variables
Simple2 u1, u2[20], *u3;

In the above declarations, the first and second declarations are treated by the compiler as two completely different types, even if their member lists are the same. If you set t3=&s1, it is illegal.

Members of a structure can contain other structures, and can also contain pointers to their own structure type. Usually, such pointers are used to implement more advanced data structures such as linked lists and trees.

// This structure declaration includes other structures
struct COMPLEX
{
    char string[100];
    struct SIMPLE a;
};

// This structure declaration contains a pointer to its own type
struct NODE
{
    char string[100];
    struct NODE *next_node;
};

If two structures contain each other, one of the structures needs an incomplete declaration, as shown below:

struct B;    // Make an incomplete declaration of structure B

// struct A contains a pointer to struct B
struct A
{
    struct B *partner;
    //other members;
};

// struct B contains a pointer to struct A; after A is declared, B is also declared.
struct B
{
    struct A *partner;
    //other members;
};

Initialization of structure variables

Like variables of other types, structure variables can be given initial values at the time of definition.

Example

#include <stdio.h>

struct Books
{
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
} book = {"C language", "EXAMPLE", "programming language", 123456};

int main()
{
    printf("title : %s\nauthor: %s\nsubject: %s\nbook_id: %d\n", book.title, book.author, book.subject, book.book_id);
}

The output after execution is:

title : C 语言
author: EXAMPLE
subject: 编程语言
book_id: 123456

Access structure members

To access the members of a structure, we useMember access operator (.)The member access operator is a period between the structure variable name and the structure member we want to access. You can usestructthe keyword to define variables of structure type. The following example demonstrates the use of structures:

Example

#include <stdio.h>
#include <string.h>
 
struct Books
{
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
};
 
int main( )
{
   struct Books Book1;        /* Declare Book1 of type Books */
   struct Books Book2;        /* Declare Book2 of type Books */
 
   /* Book1 details */
   strcpy( Book1.title, "C Programming");
   strcpy( Book1.author, "Nuha Ali");
   strcpy( Book1.subject, "C Programming Tutorial");
   Book1.book_id = 6495407;

   /* Book2 details */
   strcpy( Book2.title, "Telecom Billing");
   strcpy( Book2.author, "Zara Ali");
   strcpy( Book2.subject, "Telecom Billing Tutorial");
   Book2.book_id = 6495700;
 
   /* Output Book1 information */
   printf( "Book 1 title : %s\n", Book1.title);
   printf( "Book 1 author : %s\n", Book1.author);
   printf( "Book 1 subject : %s\n", Book1.subject);
   printf( "Book 1 book_id : %d\n", Book1.book_id);

   /* Output Book2 information */
   printf( "Book 2 title : %s\n", Book2.title);
   printf( "Book 2 author : %s\n", Book2.author);
   printf( "Book 2 subject : %s\n", Book2.subject);
   printf( "Book 2 book_id : %d\n", Book2.book_id);

   return 0;
}

When the above code is compiled and executed, it produces the following results:

Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700

Structures as function parameters

You can pass structures as function parameters, and the passing method is similar to variables or pointers of other types. You can use the method in the above example to access structure variables:

Example

#include <stdio.h>
#include <string.h>
 
struct Books
{
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
};

/* Function declaration */
void printBook( struct Books book );
int main( )
{
   struct Books Book1;        /* Declare Book1 of type Books */
   struct Books Book2;        /* Declare Book2 of type Books */
 
   /* Book1 details */
   strcpy( Book1.title, "C Programming");
   strcpy( Book1.author, "Nuha Ali");
   strcpy( Book1.subject, "C Programming Tutorial");
   Book1.book_id = 6495407;

   /* Book2 details */
   strcpy( Book2.title, "Telecom Billing");
   strcpy( Book2.author, "Zara Ali");
   strcpy( Book2.subject, "Telecom Billing Tutorial");
   Book2.book_id = 6495700;
 
   /* Output Book1 information */
   printBook( Book1 );

   /* Output Book2 information */
   printBook( Book2 );

   return 0;
}
void printBook( struct Books book )
{
   printf( "Book title : %s\n", book.title);
   printf( "Book author : %s\n", book.author);
   printf( "Book subject : %s\n", book.subject);
   printf( "Book book_id : %d\n", book.book_id);
}

When the above code is compiled and executed, it produces the following results:

Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700

Pointer to structure

You can define a pointer to a structure in a manner similar to defining pointers to variables of other types, as shown below:

struct Books *struct_pointer;

Now, you can store the address of a structure variable in the pointer variable defined above. To find the address of a structure variable, place the & operator before the structure name, as shown below:

struct_pointer = &Book1;

To access members of the structure using a pointer to the structure, you must use the -> operator, as shown below:

struct_pointer->title;

Let's rewrite the above example using structure pointers, which will help you understand the concept of structure pointers:

Example

#include <stdio.h>
#include <string.h>
 
struct Books
{
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
};

/* Function declaration */
void printBook( struct Books *book );
int main( )
{
   struct Books Book1;        /* Declare Book1 of type Books */
   struct Books Book2;        /* Declare Book2 of type Books */
 
   /* Book1 details */
   strcpy( Book1.title, "C Programming");
   strcpy( Book1.author, "Nuha Ali");
   strcpy( Book1.subject, "C Programming Tutorial");
   Book1.book_id = 6495407;

   /* Book2 details */
   strcpy( Book2.title, "Telecom Billing");
   strcpy( Book2.author, "Zara Ali");
   strcpy( Book2.subject, "Telecom Billing Tutorial");
   Book2.book_id = 6495700;
 
   /* Output Book1 information by passing the address of Book1 */
   printBook( &Book1 );

   /* Output Book2 information by passing the address of Book2 */
   printBook( &Book2 );

   return 0;
}
void printBook( struct Books *book )
{
   printf( "Book title : %s\n", book->title);
   printf( "Book author : %s\n", book->author);
   printf( "Book subject : %s\n", book->subject);
   printf( "Book book_id : %d\n", book->book_id);
}

When the above code is compiled and executed, it produces the following results:

Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700

Calculation of structure size

In C language, we can usesizeofthe operator to calculate the size of a structure,sizeofIt returns the byte size of the given type or variable.

For structures,sizeofIt will return the total number of bytes of the structure, including the sizes of all member variables and possible padding bytes.

The following example demonstrates how to calculate the size of a structure:

Example

#include <stdio.h>

struct Person {
    char name[20];
    int age;
    float height;
};

int main() {
    struct Person person;
    printf("Size of struct Person: %zu bytes\n", sizeof(person));
    return 0;
}

In the above example, we defined a struct namedPersonA structure that contains a character arrayname, an integerageand a floating-point numberheight。

InmainIn the function, we declared aPersonvariable of typeperson, then usesizeofoperator to getpersonthe size of the structure.

Finally, we useprintfThe function prints the size of the structure, and the output is as follows:

结构体 Person 大小为: 28 字节

Note, the size of a structure may be affected by the compiler's optimization and alignment rules. The compiler may insert some extra padding bytes in the structure to align the member variables of the structure, improving memory access efficiency. Therefore, the actual size of the structure may be larger than the sum of the sizes of the member variables. If you need to know exactly the memory layout and alignment of the structure, you can useoffsetofmacro and__attribute__((packed))attributes and so on to further control and query the size and alignment of the structure.

other extensions