2016年06月14日学习日记c语言结构体
&引用:给变量起一个别名(c++中使用)
typedef类型重定义:数据类型起一个别名(c语言中可使用)
结构体:struct是一种数据结构,用于表示有关联的元素的集合;
(数组:相同类型元素的集合)
定义方式:
1:只定义结构体
struct people
{
char *name;
int age;
char *sex;
};//分号不可少
初始化:
struct people peop={”lily”,20,”girl”};//初始化结构体
struct pepper peop={“lili”,20};//可以赋值,sex默认为null
访问:eg:peop.name//用’.’(结构体变量名.元素)的形式来进行访问和修改结构体元素
2:定义结构体的同时声明结构体变量
初始化:定义后不能直接初始化,就像数组不能在定义后初始化一样
struct people
{
char *name;
int age;
char *sex;
}peop;
3:类型重定义,使用typedef(最常使用方式)
typedef struct sam
{
int num1;
float num2;
char c;
}SAMPLE;//SAMPEL是struct sam的一个别名,不再是上面的变量了
声明变量:
SAMPLE sample1;//等价于第一二种方法的struct sam sample1;
SAMPLE sample2;//
结构体占用空间大小(所有元素和)
结构体所占用空间自动补齐功能:不同类型内存向最大的看齐,相邻的相同类型元素可以结合补齐,但是不能隔元素补齐。
例子:
struct s1
{
char a;
char b;
};//2累加
struct s2
{
int num;
char a;
};//4+4=8向最长的补齐(char 1->4)
struct s3
{
int num;
char a;
char b;
};//8 4+4(char a和char b)最长下方累加补齐
struct s4
{
char a;
int num;
char b;
char c;
};//12 4(a)+4(num)+4(char b和char c)最长上下方各累加补齐
struct s5
{
char a;
int num;
char b;
double c;
char d;
};//32 8(a+num)+8(b)+8(c)+8(d)最长上下方各累加补齐(最长上下不能想加)
struct s6
{
int num;
char a;
char b;
double c;
char d;
};//24 8(num+a+b)+8(c)+8(d)最长上下方各累加补齐
struct s7
{
int num;//4
char c[22];//22
};//28(补齐20/4=5个剩下两个再补齐一个4 4+20+4=28)
struct s8
{
int num;//4
char c;//1->4
};
struct s9
{
struct s8 s;//相当于加了int num;char c
char l;
};//12=(4+4+4)
结构体指针:
typedef struct sam
{
int num1;
float num2;
}SAMPLE;
SAMPLE sam1={13,3.4f};
SAMPLE *pt = &sam1;//结构体指针
printf("num1 = %d\n",(*pt).num1);//解引用得到变量再 .元素
printf("num2 = %f\n",pt->num2);//pt->元素 直接指向元素
c语言中预处理工作
预处理3种:
1:include头文件包含
‘ < > ’:包含系统资源
‘ “ ” ’:自定义资源
2:define
#define PI 3.14//没有参数,注意:define没有’=‘没有’;’
#define sum(a,b) (a)*(b)//带有参数
#define op 2
#if op=1
print(“op1\n”);
#elif
prinf(“op2\n”);
#else
printf(“op3\n”);
#endif
课堂练习:
eg:name(字符串?字符数组?)
都可以啊……
结构体练习:写一个人信息(姓名,性别,年龄,爱好)
#include <stdio.h>
int main()
{
typedef struct people
{
char *name;
char *sex;
int age;
char *hobby;
}peo;
return 0;
}
通过指针进行查看个人信息
#include <stdio.h>
int main()
{
typedef struct people
{
char *name;
char *sex;
int age;
char *hobby;
}peo;
peo p1={"lilei","女",20,"动漫"};
peo *p2 = &p1;
printf("姓名:%s\n性别:%s\n年龄:%d\n爱好:%s\n",(*p2).name,(*p2).sex,(*p2).age,p2->hobby);
return 0;
}
修改个人信息后再进行查看
#include <stdio.h>
int main()
{
typedef struct people
{
char *name;
char *sex;
int age;
char *hobby;
}peo;
peo p1={"lilei","女",20,"动漫"};
peo *p2 = &p1;
printf("姓名:%s\n性别:%s\n年龄:%d\n爱好:%s\n",(*p2).name,(*p2).sex,(*p2).age,p2->hobby);
printf("修改后————————————————\n");
p1.name="gintama";
p1.sex="男";
p1.age=0;
p1.hobby="甜食";
printf("姓名:%s\n性别:%s\n年龄:%d\n爱好:%s\n",(*p2).name,(*p2).sex,(*p2).age,p2->hobby);
return 0;
}
断点:
第一个:程序执行到下一个端点
第二个:程序执行到下一行代码
第三个:程序进入函数内(自定义函数)
第四个:程序推出函数