C语言结构体跟指针使用

//person结构体,姓名,年龄,身高,体重
//打印结构体值,增加20后再打印,用函数
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>

typedef struct  
{   
    char *name;
    int age;
    int height;
    int weight;
}Person;
    
//结构体数据赋值
Person *person_create(char *name, int age, int height, int weight)
{
    Person *who = malloc(sizeof(Person));
    assert(who != NULL);
    
    //strncpy(who->name, name, strlen(name)+1);
    who->name = strdup(name);
    who->age = age;
    who->height = height;
    who->weight = weight;

    return who;
}

void person_destroy(Person *who)
{
    free(who->name);
    free(who);
}

//打印结构体的值
void person_print(Person *who)
{
    printf("name is %s\n", who->name);
    printf("age is %d\n", who->age);
    printf("height is %d\n", who->height);
    printf("weight is %d\n", who->weight);
}

//主函数
int main(int argc, char *argv[])
{
    Person *xia = person_create("xia", 20, 170, 120);
    Person de = {"de", 20, 170, 120};
    person_print(&de);
    printf("---\n");
    
    person_print(xia);
    xia->age += 2;
    xia->height += 20;
    xia->weight += 20;
    printf("---\n");

    person_print(xia);
    person_destroy(xia);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/xiadeliang1111/article/details/60767718