首页 > 学院 > 开发设计 > 正文

C语言结构体跟指针使用

2019-11-06 06:04:04
字体:
来源:转载
供稿:网友
//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;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表