Trang chủ » C/C++ » C Structure

C Structure


Introducing to C structure

In some programming contexts, you need to access multiple data types under a single name for easier data manipulation; for example you want to refer to address with multiple data like house number, street, zip code, country. C supports structure which allows you to wrap one or more variables with different data types. A structure can contain any valid data types like int, char, float even arrays or even other structures. Each variable in structure is called a structure member.

Defining structure

To define a structure, you use struct keyword. Here is the common syntax of structure definition:

 

struct struct_name{ structure_member };

 

The name of structure follows the rule of variable name. Here is an example of defining address structure:

 

struct address{
      unsigned int house_number;
      char street_name[50];
      int zip_code;
      char country[50];
    };

The address structure contains house number as an positive integer, street name as a string, zip code as an integer and country as a string.

Declaring structure

The above example only defines an address structure without creating any structure instance. To create or declare a structure instance, you can do it in two ways:

The first way is to declare a structure followed by structure definition like this :

 

struct struct_name {
      structure_member;
      …
    } instance_1,instance_2 instance_n;

 

In the second way, you can declare the structure instance at a different location in your source code after structure definition. Here is structure declaration syntax :

struct struct_name instance_1,instance_2 instance_n;

 

Complex structure

If a structure contains arrays or other structures, it is called complex structure. For example address structure is a structure. We can define a complex structure called customer which contains address structure as follows:

 

struct customer{
      char name[50];
      structure address billing_addr;
      structure address shipping_addr;
    };

 

Accessing structure member

To access structure members we can use dot operator (.) between structure name and structure member name as follows:

structure_name.structure_member

For example to access street name of structure address we do as follows:

 

struct address billing_addr;
billing_addr.country = "US";

 

If the structure contains another structure, we can use dot operator to access nested structure and use dot operator again to access variables of nested structure.

 

struct customer jack;
jack.billing_addr.country = "US";

 

Initializing structure

C programming language treats a structure as a custom data type therefore you can initialize a structure like a variable. Here is an example of initialize product structure:

 

struct product{
      char name[50];
      double price;
    } book = { "C programming language",40.5};

In above example, we define product structure, then we declare and initialize book structure with its name and price.

Structure and pointer

A structure can contain pointers as structure members and we can create a pointer to a structure as follows:

struct invoice{
        char* code;
        char date[20];
    };
    struct address billing_addr;
    struct address *pa = &billing_addr;

 

Shorthand structure with typedef keyword

To make your source code more concise, you can use typedef keyword to create a synonym for a structure. This is an example of using typedef keyword to define address structure so when you want to create an instance of it you can omit the keyword struct

typedef struct{
          unsigned int house_number;
          char street_name[50];
          int zip_code;
          char country[50];
    } address;
    address billing_addr;
    address shipping_addr;

 

Copy a structure into another structure

One of major advantage of structure is you can copy it with = operator. The syntax as follows

 

struct_intance1 = struct_intance2

be noted that some old C compilers may not supports structure assignment so you have to assign each member variables one by one.

Structure and sizeof function

sizeof is used to get the size of any data types even with any structures. Let’s take a look at simple program:

 

#include <stdio.h>
 
typedef struct __address{
    int house_number;// 4 bytes
    char street[50]; // 50 bytes
    int zip_code; // 4 bytes
    char country[20];// 20 bytes
 
} address;//78 bytes in total
 
void main()
{
    // it returns 80 bytes
    printf("size of address is %d bytes\n",sizeof(address));
}

You will never get the size of a structure exactly as you think it must be. The sizeof function returns the size of structure larger than it is because the compiler pads struct members so that each one can be accessed faster without delays. So you should be careful when you read the whole structure from file which were written from other programs.

Source code example of using C structure

In this example, we will show you how to use structure to wrap student information and manipulate it by reading information to an array of student structure and print them on to console screen.

 

#include <stdio.h>
 
typedef struct _student{
    char name[50];
    unsigned int mark;
} student;
 
 
 
void print_list(student list[], int size);
void read_list(student list[], int size);
 
 
 
void main(){
 
    const int size = 3;
    student list[size];
    
    read_list(list,size);
 
    print_list(list,size);
 
 
}

void read_list(student list[], int size)
{
    printf("Please enter the student information:\n");
 
    for(int i = 0; i < size;i++){
        printf("\nname:");
        scanf("%S",&list[i].name);
 
        printf("\nmark:");
        scanf("%U",&list[i].mark);
    }
 
}

void print_list(student list[], int size){
    printf("Students' information:\n");
    
    for(int i = 0; i < size;i++){
        printf("\nname: %s, mark: %u",list[i].name,list[i].mark);
    }
}

Here is program’s output

 

Please enter the student information:

name:Jack

mark:5

name:Anna

mark:7

name:Harry

mark:8
Students' information:

name: J, mark: 5
name: A, mark: 7
name: H, mark: 8

Bình luận

Mời bạn điền thông tin vào ô dưới đây hoặc kích vào một biểu tượng để đăng nhập:

WordPress.com Logo

Bạn đang bình luận bằng tài khoản WordPress.com Log Out / Thay đổi )

Twitter picture

Bạn đang bình luận bằng tài khoản Twitter Log Out / Thay đổi )

Facebook photo

Bạn đang bình luận bằng tài khoản Facebook Log Out / Thay đổi )

Google+ photo

Bạn đang bình luận bằng tài khoản Google+ Log Out / Thay đổi )

Connecting to %s