C语言 结构体

1. 结构体的声明

struct    结构体名   {成员表列};

例如:

struct student{

    char name[20];

    int age;

    int num;

    };

在main函数中定义结构体变量: struct student s1, s2;

                                    使用时:s1.name;

在main函数中定义结构体指针变量: struct student s3;

                                    使用时:s3->name;

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student
{
    char name[20];
    int age;
    char sex;
};

int main()
{
    struct student s1 = {"zxy", 20, 'f'};
    struct student s2;
    struct student *s3 = (struct student*)malloc(sizeof(struct student));

    scanf("%s%d %c", s2.name, &s2.age, &s2.sex);
    
    strcpy(s3->name, "cyz");
    s3->age = 22;
    s3->sex = 'f';

    printf("%s %d %c\n", s1.name, s1.age, s1.sex);
    printf("%s %d %c\n", s2.name, s2.age, s2.sex);
    printf("%s %d %c\n", s3->name, s3->age, s3->sex);
    return 0;
}

2. 结构体长度

    原则:(1)结构体的总长度一定是最长成员的整数倍(double除外,double取4的倍数)

               (2)每个成员的偏移量,一定是该成员长度的整数倍

               (3)数组单独计算  int name[2]; 长2*4

               (4)包含结构体时,内结构体展开写入,最长成员取内外结构体的最长成员

例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct A
{
    char a[2];
};
struct student
{
    struct A aa;
    short i[20];
    char a[2];
    int age;
    int b;
    short c;
    float d;
};

int main()
{
    struct student s1;

    printf("%d\n", sizeof(struct student));
    return 0;
}

运行结果:56

3. 结构体指针数组(数组的每个元素都是一个结构体指针)

main函数中定义变量 :struct student *s[3];

例:

#include <stdio.h>
#include <stdlib.h>

struct student
{
    char name[5];
    int age;
};

int main()
{
    struct student *s[3];
    int i;
    for(i = 0; i < 3; i++)
    {
        s[i] = (struct student*)malloc(sizeof(struct student));
        scanf("%s%d", s[i]->name, &s[i]->age);
    }
    for(i = 0; i < 3; i++)
    {
        printf("%s %d\n", s[i]->name, s[i]->age);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41998576/article/details/81274305