C语言结构体

C语言结构体--Structures(1)

Basic introduction without pointer

什么是结构体?

结构体是C语言中一种复合数据类型,它允许我们将不同类型的数据组合在一起,形成一个新的数据类型

比如说最常见的int,char等类型,我们定义一个变量时候常用int a,char ch...

同样我们可以将结构体视为我们自定义的数据类型:struct Student s1 ,或者如果用了typedf的话可以这样:Student s1 。

结构体的定义方式

  • 先定义结构体类型,再定义结构体变量
#include<stdio.h>
struct Student{
    int age;
    char name[10];
};

int main(){
    struct Student s1={14,"XiaoMing"};
}

值得注意的是,在定义结构体变量的时候,用大括号可以直接初始化(如上所示)。

但是如果只是定义变量未初始化,后续想要赋值不可以用大括号统一赋值,如下打咩打咩!

#include<stdio.h>
int main(){
    struct Student s1;
    s1={14,"XiaoMing"};//报错!!!
}

可以的方法只能是结构体成员中一个个赋值

#include<stdio.h>
int main(){
    struct Student s1;
    s1.age=14;
}
  • 定义类型的同时定义变量
#include<stdio.h>
#include <string.h>
struct Student{
    int age;
    char name[10];
}s1,s2;

int main(){
    s1.age=14;
    strcpy(s1.name,"XiaoMing");
}
  • 使用typedef给结构体类型取别名

#include<stdio.h>

typedef struct {
    char name[50];
    int age;
    float score;
} Student;

int main(){
    Student s1={14,"XiaoMing"};
}

结构体数组

结构体数组可以定义一个存储多个结构体的数组:

struct Student class[40];  // 定义一个可以存储40个学生信息的数组

// 访问结构体数组成员
strcpy(class[0].name, "张三");
class[0].age = 18;
class[0].score = 95.5;

结构体嵌套

结构体的嵌套结构体中的成员也可以是另一个结构体:

struct Date {
    int year;
    int month;
    int day;
};

struct Student {
    char name[50];
    int age;
    float score;
    struct Date birthday;  // 结构体嵌套
};

// 访问嵌套结构体的成员
struct Student student1;
student1.birthday.year = 2000;
student1.birthday.month = 1;
student1.birthday.day = 1;

结构体作为函数参数

// 定义一个打印学生信息的函数
void printStudent(struct Student stu) {
    printf("姓名:%s\n", stu.name);
    printf("年龄:%d\n", stu.age);
    printf("成绩:%.1f\n", stu.score);
}

struct Student student1={"XiaoMing",14,100};
// 调用函数
printStudent(student1);
posted @ 2024-12-22 14:31  RAY5-2  阅读(57)  评论(0编辑  收藏  举报