示例1:
/*
如何使用结构体
两种方式:
struct Student st = {1000, "zhangsan", 20};
struct Student * pst = &st;
1.
st.sid
2.
pst->sid
pst所指向的结构体变量中的sid这个成员
*/
# include <stdio.h>
# include <string.h>
struct Student
{
int sid;
char name[200];
int age;
}; //分号不能省
int main(void)
{
struct Student st = {1000, "zhangsan", 20};
//st.sid = 99; //第一种方式
struct Student * pst;
pst = &st;
pst->sid = 99; //第二种方式 pst->sid 等价于 (*pst).sid 而(*pst).sid等价于 st.sid, 所以pst->sid 等价于 st.sid
return 0;
}
示例2:
# include <stdio.h>
# include <string.h>
struct Student
{
int sid;
char name[200];
int age;
}; //分号不能省
int main(void)
{
struct Student st = {1000, "zhangsan", 20};
printf("%d %s %d\n", st.sid, st.name, st.age);
st.sid = 99;
//st.name = "lisi"; //error
strcpy(st.name, "lisi");
st.age = 22;
printf("%d %s %d\n", st.sid, st.name, st.age);
//printf("%d %s %d\n", st); //error
return 0;
}
示例3:
#include<stdio.h>
#include<string.h>
typedef struct transcript //定义结构体
{
int code;
char name[20];
int goals;
}TS; //定义该结构体的第二个名字为TS
int main(){
TS ts;
TS *zzr; //定义结构体指针 *zzr
zzr = &ts; //取ts的物理地址 zzr只能存储物理地址,不能存储物理地址的数值
zzr->code = 20187629; //通过物理地址修改ts实参内的参数
strcpy(zzr->name,"小明"); //参数为字符时 需要使用strcpy()进行负值
(*zzr).goals = 100;
printf("%s的学号是%d,这次考试成绩为%d分。\n",zzr->name,zzr->code,zzr->goals);
printf("zzr的物理地址是:%d",&zzr);
return 0;
}