#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct STU // 结构体类型,不占用地址空间
{
char name[20];
short int age;
char sex[5];
char id[15];
};注意“;”,必须有
int main()
{
struct STU stu;//创建结构体变量stu的过程叫“实例化”
strcpy(stu.name, "张三"); //strcpy()字符串拷贝
strcpy(stu.sex, "男");
stu.age = 20;
strcpy(stu.id, "123456789");
printf("%s\n", stu.name);
printf("%s\n", stu.sex);
printf("%d\n", stu.age);
printf("%s\n", stu.id);
system("pause");
return 0;
}
只知道结构体stu地址时,使用指针
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct STU
{
char name[20];
short int age;
char sex[5];
char id[15];
};
void test(struct STU *pstu)
{
strcpy((*pstu).name, "张三");
strcpy((*pstu).sex, "男");
(*pstu).age = 20;
strcpy((*pstu).id, "123456789");
}
int main()
{
struct STU stu;
test(&stu);
printf("%s\n", stu.name);
printf("%s\n", stu.sex);
printf("%d\n", stu.age);
printf("%s\n", stu.id);
system("pause");
return 0;
}
使用->结构体指针->成员名
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct STU
{
char name[20];
short int age;
char sex[5];
char id[15];
};
void test(struct STU *pSTU)
{
strcpy(pSTU->name, "张三");
strcpy(pSTU->sex, "男");
pSTU->age = 21;
strcpy(pSTU->id, "123456789");
}
int main()
{
struct STU stu;
test(&stu);
printf("%s\n", stu.name);
printf("%s\n", stu.sex);
printf("%d\n", stu.age);
printf("%s\n", stu.id);
system("pause");
return 0;
}