结构体:
struct Student//结构体类型说明
{
int id;
float score;
char name[20];
}; //;不能省
int main(void)
{
int i;
struch Student s;
//struch student s = {1,95.5,"zhangsan"};初始化
//部分初始化struch student s = {.score = 95.5, .name = "zhangsan"};未初始化部分补零
//赋值
s.id = 1;//.结构体成员运算符
s.score = 95.5;
strcpy(s.name,"zhangsan");
printf("%lu\n",sizeof(struct Student));//输出28;
printf("%d,%f,%s\n",s.id,s.score,s.name);
}
结构体对齐:
为了提高效率,有意浪费几个字节
结构体对齐的规则
1、结构体按照其最长成员大小对齐,意味着最终的大小必须是最长成员大小的整数倍;
2、结构体成员按照结构体成员声明先后次序依次存放,并且每个成员的首字节放置的位置必须能够整除成员的字节数;
3、如果结构体某个成员的字节数大于CPU的字节数,则最长按照CPU的字节数对齐;
4、用预处理命令#pragma pack(n) 可以强制编译器按照指定的n来对齐,合法的n的数值分别是1、2、4、8、16。
结构体嵌套
指针传参
struct Student
{
int id;
float score;
char name[20];
};
void printStudent(struct Student *s)
{
printf("%d,%f,%s\n",(*s).id,(*s).score,(*s).name);
}
void fn(struct Student *s)
{
(*s).id += 10;//s->id:指向结构体成员运算符,左边为指针
}
int main(void)
{
struct Student s= {.id = 1,.score = 95.5,.name = "zhangsan"};
fn(&s);
printStudent(&s);
return 0;
}
结构体变量允许整体赋值;
遍历和逆序
void swap(struct Student *a,struct Student *b)//交换
{
struct Student t;
t = *a;
*a = *b;
*b = t;
}
void revsers(struct Student *a,int len)//逆序
{
int i;
for(i = 0;i < len / 2;++i)
{
swap(a + i,a + len - i - 1);
}
}
void printStudents(struct Student *a,int len)//遍历
{
int i;
for(i = 0;i < len;++i)
{
printStudent(a + i);
}
}
结构体之间无法进行大小关系比较,成员间可以进行比较;
数据结构+ 算法 = 程序;
链表:
有若干个节点(Node)组成,节点包含值域和指针域,节点从堆上来;
#include<stdio.h>
#include<stdlib.h>
struct Node //定义结构体
{
int data;
struct Node *next;
};
void push_front(struct Node *pHead,int n)//插入链表
{
struct Node *pNew = malloc(sizeof(struct Node));
pNew->next = pHead->next;
pHead->next = pNew;
pNew->data = n;
}
void printList(struct Node *pHead)//打印链表元素
{
struct Node *p = pHead->next;
while(p != NULL)
{
printf("%d,",p->data);
p = p->next;
}
puts("\b ");
}
int size(struct Node *pHead)//计算链表元素个数
{
int i = 0;
struct Node *p = pHead->next;
while(p != NULL)
{
++i;
p = p->next;
}
return i;
}
int isEmpty(struct Node *pHead)//判断是否有空指针
{
return pHead->next == NULL;
}
int main(void)
{
struct Node head = {0,NULL};
printf("isEmpty = %d\n",isEmpty(&head));
push_front(&head,1);
push_front(&head,2);
push_front(&head,3);
push_front(&head,4);
printList(&head);
printf("%d\n",size(&head));
printf("isEmpty = %d\n",isEmpty(&head));
return 0;
}