天天看點

程式員之路: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

繼續閱讀