step2 . day5 C语言中的结构体和枚举
最近幾天交叉的學習C和Linux,知識梳理的不是很仔細,有很多還沒有搞明白的問題,所有耽誤了幾天更新筆記,也是在細嚼慢咽中,做了一個規劃表,現階段先把C后面的知識學好,然后再梳理Linux系統相關知識,爭取在本月做完匯總,把step1和step2的目標達成。
1. 枚舉類型及使用
#include<stdio.h>
enum calc_t{
add,
sub,
mul,
div,
mod
};
int mycalc(int a,int b,enum calc_t c)
{
switch(c){
case add:return a+b;break;
case sub:return a-b;break;
case mul:return a*b;break;
case div:return a/b;break;
case mod:return a%b;break;
default:
printf("error!\n");break;
}
}
int main(int argc, const char *argv[])
{
printf("a + b =%d\n",mycalc(3,4,add));
printf("a - b =%d\n",mycalc(3,4,sub));
printf("a * b =%d\n",mycalc(3,4,mul));
printf("a / b =%d\n",mycalc(3,4,div));
printf("a %% b =%d\n",mycalc(3,4,mod));
return 0;
}
注意,枚舉的數據類型測試是4個字節,不知道為啥,還在研究中
2. 結構體的聲明和賦值:
#include<stdio.h>
struct student{
int id;
int score;
}stu[3] = {1,2,3,4,5,6};
int main(int argc, const char *argv[])
{
struct student stu1[2] = {{7,8},{9,10}};
struct student stu2[2] = {
[0] = {11,12},
[1] = {13,14}
};
struct student stu3[2] = {
{.id = 15,.score = 16},
{17,18}
};
struct student stu4[2];
stu4[0].id = 19;
stu4[1].score =20;
return 0;
}
3.結構體的使用
#include<stdio.h>
#include<string.h>
struct student{
char name[32];
int age;
int id;
int score;
};
void stu_info_input(struct student *stu){
// char nametem[32];
printf("********************************\n");
printf("please input student's name:");
scanf("%s",stu->name);
// strcpy(stu->name,nametem);
printf("please input student's age:");
scanf("%d",&stu->age);
printf("please input student's id:");
scanf("%d",&stu->id);
printf("please input student's score:");
scanf("%d",&stu->score);
}
void stu_info_output(struct student *stu){
printf("Name\tAge\tID\tScore\n");
printf("%s\t%d\t%d\t%d\n",stu->name,stu->age,stu->id,stu->score);
}
int main(int argc, const char *argv[])
{
struct student stu,*s;
s = &stu;
stu_info_input(s);
stu_info_output(s);
return 0;
}
?
4.結構體的大小(sizeof(struct name)),遵從數據對齊方式,是最大數據長度的整數倍,
char占用一個字節? ?
short占用兩個,內存需要從0,2,4,6,8,開始存儲,
int 占4個字節? 存儲需從0,4,8等被整除的位置開始存儲
double為特殊,占8個字節,則是從4開始,同int存儲位置。內存補齊遵守原則要牢記
?
轉載于:https://www.cnblogs.com/huiji12321/p/11196837.html
總結
以上是生活随笔為你收集整理的step2 . day5 C语言中的结构体和枚举的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 非UI线程操作UI
- 下一篇: 技术人员转型是件痛苦的事情~