C程序基础笔记之结构体

141 阅读1分钟
  • 结构体是一种数据结构
  • 是复合数据类型的一种
  • 可以被声明为变量、指针和数组

struct 一般用法

#include <stdio.h>
// 声明
struct student {
    int id;
    char *name;
};

void printStu(struct student *stu) {
    printf("student info :id: %d,name:%s\n", stu->id, stu->name);
}

int main() {
    // 定义
    struct student stu1;
    stu1.id = 101;
    stu1.name = "张三";
    printStu(&stu1);

    // 定义并初始化
    struct student stu2 = {102, "李四"};
    printStu(&stu2);

    // 指针化定义
    struct student *stu3 = malloc(sizeof(struct student));
    stu3->id = 103;
    stu3->name = "王五";
    printStu(stu3);
    free(stu3);

    return 0;
}

struct 与 typedef 结合使用

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

// 声明
typedef struct {
    int id;
    char *name;
} student;


void printStu(student *stu) {
    printf("student info :id: %d,name:%s\n", stu->id, stu->name);
}

int main() {
    student stu1;
    stu1.id = 101;
    stu1.name = "张三";
    printStu(&stu1);

    student stu2 = {102, "李四"};
    printStu(&stu2);

    student *stu3 = malloc(sizeof(student));
    stu3->id = 103;
    stu3->name = "王五";
    printStu(stu3);
    free(stu3);

    return 0;
}

自定义字符串

#include <stdlib.h>
#include <string.h>

struct vstring {
    int len;
    char chars[];
};

void printStr(struct vstring *str) {
    printf("value:%s\n", str->chars);
}

int main() {

    int n = 20;
    struct vstring *str = malloc(sizeof(struct vstring) + n * sizeof(char));
    str->len = n;
    strcpy(str->chars, "hello world");
    printStr(str);
    free(str);

    return 0;
}

GNU C 扩展 : 指定初始化

#include <stdio.h>

struct student
{
    int id;
    char *name;
};

void printStu(struct student *stu)
{
    printf("student info :id: %d,name:%s\n", stu->id, stu->name);
}

// gcc struct_test.c && ./a.out
int main()
{
    // 指定初始化
    struct student stu = {
        .id = 104,
        .name = "mcc"};
    printStu(&stu);

    // 指定初始化:部分赋值
    struct student stu2 = {
        .name = "lisi"};
    printStu(&stu2);
    return 0;
}

该用法参考自# 指定初始化