• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

C程序基础笔记:结构体

武飞扬头像
morningcat2018
帮助2

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

struct 一般用法

// 声明
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 结合使用

// 声明
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;
}

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbacbg
系列文章
更多 icon
同类精品
更多 icon
继续加载