数据结构预备知识二(指针与结构体)
一、指针知识补充
- 不管指针变量指向的变量本身所占空间是多少,指针变量本身只占4个字节
- 利用函数修改某个变量的值,只需将变量的地址发送给函数形参即可
#include <stdio.h>
#include <stdlib.h>
//利用函数修改指针变量的值
void f(int **p);
int main()
{
int i = 0 ;
int *p = &i;
printf("%p\n", p);
f(&p);
printf("%p\n", p);
return 0;
}
//注意在实际操作中并不能这样改写,这样会造成程序错误
f(int **p){
*p = (int *)0xFFFFFFFF;
}
二、结构体
- 为什么会出现结构体?
为了表示一些复杂的数据,而普通的基本数据类型变量无法满足要求。
- 什么叫结构体?
结构体是用户根据实际需要自己定义的复合数据类型。
- 如何使用结构体?
struct Student st = {10000, "zahngsan", 18};
struct Student *pst = &st;
方式一:
st.sid;
方式二:
pst->sid;
三、结构体案例
#include<stdio.h>
#include<string.h>
//修改结构体变量函数声明
void modifyStruct(struct Student *pst);
//打印结构体变量函数声明
void printStruct(struct Student st);
void printStruct1(struct Student* pst1);
struct Student{
int sid;
char name[200];
int age;
};
int main(void){
//定义结构体变量,并对其进行初始化
struct Student st = {10000, "zahngsan", 18};
struct Student *pst = &st;
struct Student st1;
st1.sid = 10001;
strcpy(st1.name, "lisi");
st1.age = 18;
printStruct1(pst);
printStruct(st1);
modifyStruct(pst);
printStruct1(pst);
}
//定义方法对结构体变量进行修改
modifyStruct(struct Student *pst){
pst->sid = 10002;
strcpy(pst->name, "wangwu");
pst->age = 20;
}
//定义方法,通过将结构体变量传递给形参对结构体变量打印,但实际应用过程中,并不会使用这种方法,它浪费时间和空间
printStruct(struct Student st){
printf("sid = %d, name = %s, age = %d\n", st.sid, st.name, st.age);
}
//定义方法,通过将结构体指针变量传递给形参对结构体变量打印
printStruct1(struct Student *pst1){
printf("sid = %d, name = %s, age = %d\n", pst1->sid, pst1->name, pst1->age);
}