C语言结构体跟指针使用
来源:互联网 发布:游戏编程精粹9 pdf 编辑:程序博客网 时间:2024/05/16 15:12
//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;
}
//打印结构体值,增加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;
}
0 0
- C语言结构体跟指针使用
- c语言结构体指针
- C语言---结构体指针
- 【C语言】结构体指针
- C语言指针-----指针与结构体
- C语言结构体指针在函数调用中的使用
- C语言结构指针
- C语言--结构体中的指针
- c语言结构体指针初始化
- C语言--结构体中的指针
- c语言 结构体 指针变量
- C语言--结构体中的指针
- C语言--结构体中的指针
- C语言中的结构体指针
- c语言结构体指针初始化
- c语言结构体数组指针
- c语言结构体指针初始化
- c语言结构体指针成员初始化
- 热身之回家养猪
- ZooKeeper 常用四字命令
- 创建bmp图片方法
- 153. Find Minimum in Rotated Sorted Array
- 代收代扣代付
- C语言结构体跟指针使用
- HTML5 hgroup元素
- [转] C++11 并发指南系列
- windows批处理文件设置环境变量,包含路径、库目录等
- Yii memcache缓存
- Git的常用命令,大白话解释,让你快速上手
- Java读取Properties文件工具类
- 自定义UIAlertView、UIActionSheet,高仿系统UIAlertView、UIActionSheet
- 25作业