? ? ? 今天給大家分享C語言中結構體的幾種常見使用方法,包括基礎結構體定義與初始化,結構體指針的兩種訪問方式,結構體數組的遍歷,動態內存分配與結構體使用,typedef簡化結構體類型
基礎結構體定義與使用
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>;// 定義一個學生結構體
struct student {char name[20]; // 姓名int num; // 學號float score; // 分數
};int main()
{// 結構體變量初始化struct student s1 = {"zhangsan",10001,99.21};// 打印結構體成員printf("%s\n %d\n %.2f\n", s1.name, s1.num, s1.score);// 聲明結構體變量struct student s2;// 從輸入獲取結構體成員值scanf("%s %d %f",&s2.name,&s2.num,&s2.score); //.2的格式不能用在scanf里面 printf("%s\n %d\n %.2f\n", s2.name, s2.num, s2.score);// 結構體數組struct student sarr1[3];scanf("%s %d %f", &sarr1[0].name, &sarr1[0].num, &sarr1[0].score);printf("%s\n%d\n%.2f\n", sarr1[0].name, sarr1[0].num, sarr1[0].score);return 0;
}
結構體指針操作
struct student {char name[20]; // 姓名int id; // 學號float score; // 分數
};int main()
{struct student s1 = { "wangwu",10086,99.98 };// 定義結構體指針并指向s1struct student* ps1 = &s1;// 通過指針訪問結構體成員 - 方法1printf("%-s ,%-d ,%-.2f\n", (*ps1).name, (*ps1).id, (*ps1).score);// 通過指針訪問結構體成員 - 方法2(更常用)printf("%-s ,%-d ,%-.2f", ps1->name,ps1->id,ps1->score);return 0;
}
結構體數組與指針遍歷
struct student {char name[20]; // 姓名int id; // 學號float score; // 分數
};int main()
{// 初始化三個學生結構體struct student s1 = { "zhangsan",10086,88.9 };struct student s2 = { "lisi",10087,98.9 };struct student s3 = { "wangwu",10088,89.9 };// 結構體數組初始化struct student arr1[3] = { s1,s2,s3 };// 結構體指針指向數組首地址struct student* p = arr1;int i = 0;// 遍歷結構體數組for (i = 0; i < 3; i++){printf("%-s\n%-d\n%-.2f\n", p[i].name, p[i].id, p[i].score);}return 0;
}
動態內存分配與結構體
struct student {char name[20]; // 姓名int id; // 學號float score; // 分數
};int main()
{// 聲明結構體指針struct student* ps1;// 動態分配內存ps1 = malloc(sizeof(struct student));// 賦值操作strcpy(ps1->name,"wangdao"); // 字符串賦值需要使用strcpyps1->id = 1235;ps1->score = 99.86;printf("%-s ,%-d ,%-.2f", ps1->name, ps1->id, ps1->score);return 0;
}
使用typedef簡化結構體
// 使用typedef定義結構體別名
typedef struct student {char name[20]; // 姓名int id; // 學號float score; // 分數
}stu,*pstu; // stu == struct student; pstu == struct student *; int main()
{// 使用別名聲明變量stu s1 = { "wangwu",10081, 90.81 };pstu p1 = &s1; // p1是指向stu類型的指針return 0;
}// typedef也可以用于基本數據類型
typedef int INTEGER; // 將int定義為INTEGER
int main()
{INTEGER num = 0; // 等同于int num = 0;printf("%d\n", num);return 0;
}