1.结构体的定义、初始化、打印输出
#include <stdio.h>
#include <string.h>
struct Student{ // 定义结构体 Student
char name[30];
int age;
float gpa;
}; //记得定义结构体也是一个语句,需要加;
int main(int argc,char* argv[])
{
struct Student students[3]; // 定义结构体数组 ,也可以在定义时直接初始化,
//初始化
strcpy(students[0].name,"zhangsan");
students[0].age = 20;
students[0].gpa = 3.5;
strcpy(students[1].name,"lisi");
students[1].age = 21;
students[1].gpa = 3.7;
strcpy(students[2].name,"wangwu");
students[2].age = 22;
students[2].gpa = 3.9;
for(int i = 0; i < 3; i++){ // 循环打印输出,直接获取值。
printf("Name: %s Age: %d GPA: %f
\n",students[i].name,students[i].age,students[i].gpa);
}
return 0;
}
输出结果:
2.使用malloc动态分配内存
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Student{ // 定义结构体
char name[50];
int age;
float gpa;
};
int main(int argc,char* argv[])
{
int n;
printf("Enter the number of students:"); // 获取数量
scanf("%d",&n);
// 动态分配内存
struct Student *students = (struct Student*)malloc(n * sizeof(struct Student));
if(students == NULL){
printf("Memory allocation failed\n");
return 1;
}
// 初始化
for(int i = 0;i < n;i++){
printf("Enter name,age,and GPA for student:\n",i+1);
scanf("%s %d %f",&students[i].name,&students[i].age,&students[i].gpa);
}
// 输出
for(int i = 0;i < n;i++){
printf("Name : %s Age: %d GPA: %f\n",students[i].name,students[i].age,students[i].gpa);
}
// 释放内存
free(students);
return 0;
}
结果为:
3.结构体数组作为参数传入函数
#include <stdio.h>
struct Student{ // 定义结构体
char name[50];
int age;
float gpa;
};
printStudent(struct Student *students,int n); //声明函数
int main(int argc,char* argv[])
{
struct Student students[3] = { // 初始化结构体数组
{"zhangsan",28,3.1},
{"lisi",21,3.4},
{"wangwu",20,3.5}
};
printStudent(students,3); // 调用函数,并且传入结构体数组和长度
return 0;
}
int printStudent(struct Student *students,int n){ // 定义函数,
for(int i = 0; i < n;i++){
printf("name: %s ,age: %d,GPA: %f\n",students[i].name,students[i].age,students[i].gpa);
}
}
4.多维指针数组的访问
#include <stdio.h>
struct Student{
char name[50];
int age;
float gpa;
};
int main(int argc,const char* argv[])
{
// 初始化
struct Student students[3][2] = { // 对多维结构体指针初始化
{{"zhanngsan",18,3.2},{"zhangwu",19,3.3}},
{{"lisi",26,3.2},{"liwu",21,3.8}},
{{"wangwu",27,3.0},{"wangliu",25,3.9}}
};
for(int i = 0;i < 3;i++) // 循环打印输出
for(int j = 0;j < 2;j++)
printf("name: %s,age: %d,GPA:%f\n",students[i][j].name,students[i][j].age,students[i][j].gpa);
return 0;
}
结果为:
5.使用结构体指针访问结构体
#include <stdio.h>
#include <string.h>
// 定义一个结构体
struct Person {
char name[50];
int age;
float height;
};
int main() {
struct Person person1; // 定义一个结构体变量
struct Person *ptr; // 定义一个结构体指针
// 给结构体变量赋值
strcpy(person1.name, "张三");
person1.age = 25;
person1.height = 170;
// 将指针指向结构体变量的地址
ptr = &person1;
/ 使用指针访问结构体成员
printf("Using pointer:\n");
printf("Name: %s\n", ptr->name); // 使用 -> 运算符访问结构体成员
printf("Age: %d\n", ptr->age); /
printf("Height: %.1f\n", ptr->height);
return 0;
}
标签:name,students,age,struct,C语言,int,Student,结构
From: https://blog.csdn.net/qq_61958489/article/details/142793631