C zero-based video structure pointer -40-

Definition of the structure pointer

The pointer defines the basic data structure similar to the structure of the pointer, using the "*" symbol to:

#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;
}

Structure using pointer references to a structure member

Also support structure pointer to take the contents, constants subtraction operation, substantially similar to the same data structure pointers, not described herein again.
Structure pointer by "->" operator, can refer to structure members:

#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;
}

Structure pointer passed as parameters

If a function requires the use of the structure, then the structure is generally recommended to use a pointer as an argument, it has two advantages:

  • Passing only a pointer address, rather than copying the entire structure, space saving stack to pass parameters
  • Internal structure of the modification function, the function can be applied to the outside
#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;
}

Guess you like

Origin www.cnblogs.com/shellmad/p/11695653.html