首页 > 其他 > 详细

C零基础视频-40-结构体指针

时间:2019-10-18 00:22:38      阅读:76      评论:0      收藏: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;
    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;
}

C零基础视频-40-结构体指针

原文:https://www.cnblogs.com/shellmad/p/11695653.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!