c语言——结构体基础概念
对结构体变量可以在定义时指定初始值
struct Person
{
char name[64];
int age;
}person = { "John", 100 };
void test01()
{
//strcpy(person.name, "Lily");
//person.age = 100;
printf("Name:%s Age:%d\n", person.name, person.age);
struct Person p;
}
运行
Name:John Age:100
在栈上、在堆上分配结构体变量空间
//单个结构体变量
void test02()
{
//在栈上分配结构体变量空间
//struct Person person = { "Hanmeimei", 30 };
//printf("Name:%s Age:%d\n",person.name,person.age);
//在堆上分配结构体变量空间
struct Person* person = malloc(sizeof(struct Person));
strcpy(person->name, "Lilei");
person->age = 30;
printf("Name:%s Age:%d\n", person->name, person->age);
}
运行
Name:Lilei Age:30
多个结构体变量
//多个结构体变量
void test03()
{
//在栈上分配结构体数组空间
struct Person persons[] = {
{ "aaa", 20 },
{ "bbb", 30 },
{ "ccc", 40 },
{ "ddd", 50 },
{ "eee", 60 },
{ "fff", 70 },
};
int len = sizeof(persons) / sizeof(struct Person);
printPersons(persons, len);
//在堆上分配结构体数组空间
struct Person* ps = malloc(sizeof(struct Person) * 6);
for (int i = 0; i < 6; ++i)
{
sprintf(ps[i].name, "Name_%d", i + 1);
ps[i].age = 100 + i;
}
printPersons(ps, 6);
}
打印函数
void printPersons(struct Person* persons, int len)
{
for (int i = 0; i < len; ++i)
{
printf("Name:%s Age:%d\n", persons[i].name, persons[i].age);
}
}
运行
Name:aaa Age:20
Name:bbb Age:30
Name:ccc Age:40
Name:ddd Age:50
Name:eee Age:60
Name:fff Age:70
Name:Name_1 Age:100
Name:Name_2 Age:101
Name:Name_3 Age:102
Name:Name_4 Age:103
Name:Name_5 Age:104
Name:Name_6 Age:105