结构体指针的定义
结构体指针的定义与基本数据结构的指针类似,使用"*"符号即可:
#include <stdio.h> struct tagPetDog{ char szName[20]; char szColor[20]; char nWeight; }; int main(int argc, char* argv[]) { tagPetDog dog = { "旺财", "黄色", 5 }; tagPetDog* pDog = &dog; return 0; }
使用结构体指针引用结构体成员
结构体指针也支持取内容,加减常数等操作,同基本数据结构的指针类似,在此不再赘述。
结构体指针通过"->"运算符,可以引用结构体成员:
#include <stdio.h> struct tagPetDog{ char szName[20]; char szColor[20]; char nWeight; }; int main(int argc, char* argv[]) { tagPetDog dog = { "旺财", "黄色", 5 }; tagPetDog* pDog = &dog; printf("%s 颜色:%s, 体重:%d公斤\r\n", pDog->szName, pDog->szColor, pDog->nWeight); return 0; }
结构体指针作为函数参数传递
如果某个函数需要使用结构体,那么一般推荐使用结构体指针作为参数,它有两个好处:
- 只传递一个指针地址,而不是复制整个结构体,节省传参时的栈空间
- 函数内部对结构体的修改,可以作用到函数外部
#include <stdio.h> struct tagPetDog{ char szName[20]; char szColor[20]; char nWeight; }; void FunAddWeight(tagPetDog* pDog, int nAddWeight) { pDog->nWeight += nAddWeight; } int main(int argc, char* argv[]) { tagPetDog dog = { "旺财", "黄色", 5 }; tagPetDog* pDog = &dog; printf("%s 颜色:%s, 体重:%d公斤\r\n", pDog->szName, pDog->szColor, pDog->nWeight); FunAddWeight(pDog, 10); printf("%s 颜色:%s, 体重:%d公斤\r\n", pDog->szName, pDog->szColor, pDog->nWeight); return 0; }