您当前的位置: 首页 >  c语言

彭世瑜

暂无认证

  • 0浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

彭世瑜 发布时间:2017-11-01 11:43:04 ,浏览量:0

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

1、首先看个例子:

//typedef与struct
#include 
#include   //使用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 
#include   //使用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 
#include   //使用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 
#include   //使用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

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.3777s