程序员之路:C语言typedef和struct

学习C语言的时候,发现typedef和struct这个有点迷糊,继续学习,发现也不是特别难,正好抽时间总结一下。


1、首先看个例子:

//typedef与struct
#include <stdio.h>
#include <string.h>  //使用strcpy();

//结构定义,Student是一个Tag标签,区分其他结构
struct Student
{
    char name[50];
    int  age;
    float score;
};

int main(){
    // 声明
    struct Student student;

    // 使用赋值
    strcpy(student.name,"Tom");
    student.age=25;
    student.score=99.0;

    // 使用读取
    printf("student.name : %s\n",student.name);
    printf("student.age : %d\n",student.age);
    printf("student.score : %.2f\n",student.score);

    return 0;
}

不难看出,我在main函数之前定义了一个struct Student结构,存储学生的姓名,年龄,分数

注意:struct Student结构大括号{}后面有一个分号“;”,相当于一条语句。

main函数中,对struct Student结构进行了使用


2、下面继续:

//typedef与struct
#include <stdio.h>
#include <string.h>  //使用strcpy();

//结构定义,Student是一个Tag标签,区分其他结构
struct Student
{
    char name[50];
    int  age;
    float score;
} student;//变量

int main(){
    // 使用赋值
    strcpy(student.name,"Tom");
    student.age=25;
    student.score=99.0;

    // 使用读取
    printf("student.name : %s\n",student.name);
    printf("student.age : %d\n",student.age);
    printf("student.score : %.2f\n",student.score);

    return 0;
}

这个例子,和第1个例子中,区别在于:

(1)struct Student结构大括号后面多了一个student(注意大小写,c语言区分大小写);

(2)main函数中,我并没有单独声明student,就直接使用了。其实,在定义的时候,student(小写)就是声明的变量;

其实这两种方式是一样的。


3、看第三个例子

//typedef与struct
#include <stdio.h>
#include <string.h>  //使用strcpy();

//结构定义,Student是一个Tag标签,区分其他结构
typedef struct Student
{
    char name[50];
    int  age;
    float score;
} Student;//别名

int main(){
    //申明
    Student student;
    // 使用赋值
    strcpy(student.name,"Tom");
    student.age=25;
    student.score=99.0;

    // 使用读取
    printf("student.name : %s\n",student.name);
    printf("student.age : %d\n",student.age);
    printf("student.score : %.2f\n",student.score);

    return 0;
}

例子中,多加了一个typedef,相当于给struct Student  取了一个别名:Student,这个例子就和第1个例子很像了,只是申明的时候少写了一个struct

例2,和例3,同样在struct大括号后面写的字符串,例2表示:变量,例3表示:别名


4、当然,也可以使用指针

//typedef与struct
#include <stdio.h>
#include <string.h>  //使用strcpy();

//结构定义,Student是一个Tag标签,区分其他结构
typedef struct Student
{
    char name[50];
    int  age;
    float score;
} Student;//别名

int main(){
    //申明
    Student student;
    Student *pStudent=&student;
    // 使用赋值
    strcpy(pStudent->name,"Tom");
    pStudent->age=25;
    pStudent->score=99.0;

    // 使用读取
    printf("student.name : %s\n",pStudent->name);
    printf("student.age : %d\n",pStudent->age);
    printf("student.score : %.2f\n",pStudent->score);

    return 0;
}

好了,先写到这里,以后再补充,欢迎大家批评指正。

欢迎交流     博主QQ:1940607002

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值