一、结构体
结构体是一些值的集合,这些值称为成员变量,结构体的每个成员可以是不同类型的变量
结构体的声明
struct str
{
member-list;
}variable-list;
例如
typedef struct stu
{
char name[20];
int age;
char sex[5];
char id[20];
}Stu;//定义了结构体变量Stu
int main()
{
struct stu Put;//定义了结构体变量Put
return 0;
}
结构体成员可以是标量、数组、指针、或者其他的结构体
struct Point
{
int x;
int y;
}p1;//声明结构体变量的同时定义结构体变量
struct Point p2;//定义结构体变量
struct Point p3 = { x, y };//定义结构体变量同时初始化
struct Stu //类型声明
{
char name[20];
int age;
};
struct Stu s = { "zhangsan", 20 };//初始化
struct Node
{
int date;
struct Point p;
struct Node* next;
}n1 = { 10, {4,5},NULL };//结构体嵌套初始化
struct Node n2 = { 20, { 5, 6 }, NULL };//结构体嵌套初始化
//使用 . 访问age成员
struct S
{
char name[20];
int age;
}s;
strcpy(s.name, "zhangsan");
s.age = 20;
//结构体指针
#include <stdio.h>
#include <stdlib.h>
struct Stu//定义结构体。
{
char name[20];//结构体成员
int age;
};
void Print(struct Stu* ps)
{
printf("name=%s age=%d\n", (*ps).name, (*ps).age);//使用结构体指针访问指针指向对象的成员
printf("name=%s age=%d\n", ps->name, ps->age);//用->解引用访问ps指向的结构体中的成员
}
int main()
{
struct Stu s = { "zhangsan", 20 };
printf(&s);//结构体传参用传址传参。
system("pause");
return 0;
}
//结构体传参
//结构体传参不会降维
#include <stdio.h>
struct Stu//定义结构体。
{
char date[1000];//结构体成员
int num;
};
struct Stu s={ {1,2,3,4}, 1000 };
void Print1(struct Stu s)//传结构体传参
{
printf("%d\n",s.num);
}
void Print2(struct Stu* ps)//传址传参
{
printf("%d\n",ps->num);
}
int main()
{
Print1(s);//结构体传参用传址传参。
Print2(&s);//结构体传参用传址传参。
system("pause");
return 0;
}
例:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
struct Stu//定义结构体。
{
char name[20];//结构体成员
short age;
float weight;
};
int main()
{
int a = 10;
int* p = &a;
struct Stu s = {"张三", 20, 55.5};//定义结构体变量s,并按顺序赋初值。
struct Stu* ps = &s;//定义结构体指针变量
//printf("%s %d %f\n", (*ps).name, (*ps).age, (*ps).weight);
printf("%s %d %f\n", ps->name, ps->age, ps->weight);
//printf("%s %d %f\n", s.name, s.age, s.weight);
system("pause");
return 0;
}