结构体数组和指针
173字小于1分钟
2024-09-23
结构体数组和指针
结构体数组
struct Student {
int id;
int age;
char * name;
};
int main() {
struct Student arr[] = [{1,2,"大明"}];
printf("%d",arr[0].age);
}
指针
struct Student {
int id;
int age;
char * name;
};
int main() {
struct Student arr = {1,2,"大明"};
struct Student * p = &arr;
printf("%d",(*p).age);
// ↓ 简化写法
printf("%d",p->age);
}
传递结构体
struct Student {
int id;
int age;
char * name;
};
void test(struct Student student) {
student.id = 2;
}
void test2(struct Student * student) {
student->id = 2;
}
int main() {
struct Student arr = {1,2,"大明"};
test(arr);
// ↓ 没有变化
printf("%d",arr.id);
// 如果需要修改那就需要使用指针
test2(&arr);
// ↓ 有变化
printf("%d",arr.id);
}