C is defined using the zero-based video structure -39-

Why use structure

Things in life, tend to have a variety of attributes, and we express them in order to record, you need a thing around, multi-record data.
As a pet dog, he may have: name, color, weight.
We can use three different variables recorded it:

#include <stdio.h>

int main(int argc, char* argv[])
{
    char szName[20] = { "旺财" };
    char szColor[20] = { "黄色" };
    int nWeight = 5;

    printf("%s 颜色:%s, 体重:%d公斤\r\n", szName, szColor, nWeight);
    return 0;
}

However, after all these variables are independent of each other, in addition to pay attention to their own programmers, there is no other way to emphasize the grammar from the three variables point to the same thing.
For this reason, C language invented structure , he is in a nonessential data types , it can be a variety of combinations of the data types for the new data .

Defining and using structure

The definition of the structure

Keyword structure is struct, declaring a new data type, its syntax is as follows:

struct <结构体类型名> {
    <成员类型1> <成员变量名1>;
    <成员类型2> <成员变量名2>;
    ……
};

For example, we declare a structure of type Dog:

struct tagPetDog{
    char szName[20];
    char szColor[20];
    char nWeight;
};

Definition of the structure variable

Once defined structure type, we can use this new type , to declare a new variable , the statement and the underlying data types as:

<类型名称> <变量名>

such as:

#include <stdio.h>

struct tagPetDog{
    char szName[20];
    char szColor[20];
    char nWeight;
};

int main(int argc, char* argv[])
{
    struct tagPetDog dog1;
    struct tagPetDog dog2;
    return 0;
}

At the same time you can also declare the structure type, declare a variable name:

struct tagPetDog{
    char szName[20];
    char szColor[20];
    char nWeight;
}dog1, dog2;

But this is likely to cause confusion tag management, use less in engineering practice.

With an array of similar structures can be simultaneously initialized variable is defined:

struct tagPetDog dog1 = { "旺财", "黄色", 5 };

Refer to members of the structure

After declaring the structure variables, we can. "" Symbolic references among the members.

#include <stdio.h>

struct tagPetDog{
    char szName[20];
    char szColor[20];
    char nWeight;
};

int main(int argc, char* argv[])
{
    struct tagPetDog dog1 = { "旺财", "黄色", 5 };
    printf("%s 颜色:%s, 体重:%d公斤\r\n", dog1.szName, dog1.szColor, dog1.nWeight);
    return 0;
}

As can be seen, so that more data polymerization, easy to understand and manage.

Guess you like

Origin www.cnblogs.com/shellmad/p/11695646.html