In C language programming, we can actually open the constraints of the programming language and define the data types we want. As long as we remember the two keywords struct and typedef, we can save non-homogeneous data types through data structures and unions in C language.

define new data types

First, enter the following code in the C language online compiler :

 typedef struct student_structure {
    char* name;
    char* surname;
    int year_of_birth;
} student;

When done, this code will pre-store student as a reserved word, so we can create variables of type student.

So how exactly is this new variable formed?
The structured new variable we created is made up of a series of base variables. In the above code, we put the variables of char name and char surname into a new student variable, which is actually placed under a name of the memory block.

Use new data types

Now that we have created the new student variable, we can initialize some properties for it in the C language online compiler :

 student stu;
 
   strcpy(stu.name, "John");
   strcpy(stu.surname, "Snow"); 
   stu.year_of_birth = 1990;
 
   printf("Student name : %s\n", stu.name);
   printf("Student surname : %s\n", stu.surname);
   printf("Student year of birth : %d\n", stu.year_of_birth);

In the above example, eagle-eyed you may have noticed that we need to assign a value to all variables of the new data type. In addition to using stu.name to access, we can also use a shorter way to assign values to these structures:

 typedef struct {
   int    x;
   int    y;
} point;

point image_dimension = {640,480};

You can also set the values in a different order:
point img_dim = { .y = 480, .x = 640 };

Union vs Structure

Unions are specified in the same way as structs, but they are not the same. In a union, we can only use the same type of data. like this:

 typedef union {
      int circle;
      int triangle;
      int ovel;
} shape;

Union will only be used if the data types are the same. We can try our new data type in the C online compiler :

 typedef struct {
      char* model;
      int year;
} car_type;

typedef struct {
      char* owner;
      int weight;
} truck_type;

typedef union {
  car_type car;
  truck_type truck;
} vehicle;

Other Tips

  • When we use the & operator to create a pointer to a struct, we can also express it using the special -> inflix operator.
  • In the C language online compiler , we can even use our new data types arbitrarily like the basic data types.
  • We can copy or specify the values of structs, but we can't compare them!

TeamCode
23 声望14 粉丝

TeamCode - 云端协作开发平台,重构开发流程,提供基于云端开发的一站式工具和服务,持续自动生成开发环境、构建和部署项目,帮助开发者云端协作开发。