0%

C/C-结构体

结构体

访问结构体成员

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "stdio.h"
#include "string.h"
struct Students{
char Name[20];
double ID;
} sd1={"Python",1};
int main()
{
printf("%sID:%.0lf",sd1.Name,sd1.ID);
printf("\n");
}
/*输出结果为
PythonID:1
*/

将结构体传给函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
	#include "stdio.h"
#include "string.h"
struct Students{
char Name[20];
double ID;
} ;
void happy(struct Students sd);
int main()
{
struct Students sd1;//声明sd1,类型为Studens
struct Students sd2;
/*详述sd1*/
strcpy(sd1.Name, "Pyhton");
sd1.ID=1;
/*详述sd2*/
strcpy(sd2.Name, "C");
sd2.ID=2;
/*传递*/
happy(sd1);
happy(sd2);



}
void happy(struct Students sd)
{
printf("(%s)ID:%0.lf",sd.Name,sd.ID);
printf("\n");
}
/*输出结果:
(Pyhton)ID:1
(C)ID:2
*/

指向函数的指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include "stdio.h"
#include "string.h"
struct Students{
char Name[20];
double ID;
} ;
void happy(struct Students *sd);
int main()
{
struct Students sd1;//声明sd1,类型为Studens
struct Students sd2;
/*详述sd1*/
strcpy(sd1.Name, "Pyhton");
sd1.ID=1;
/*详述sd2*/
strcpy(sd2.Name, "C");
sd2.ID=2;
/*传递*/
happy(&sd1);
happy(&sd2);



}
void happy(struct Students *sd)
{
printf("(%s)ID:%0.lf",sd->Name,sd->ID);
printf("\n");
}
/*输出结果:
(Pyhton)ID:1
(C)ID:2
*/
//注意和传递结构体给函数的区别