C语言结构体与内存分配实战解析
1. 结构体与指针的基础运用
在C语言编程中,结构体(struct)是一种强大的数据组织工具,它允许我们将不同类型的数据组合在一起,形成一个新的复合数据类型。下面我们通过一个示例程序来深入了解结构体和指针的使用。
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
struct Person {
char *name;
int age;
int height;
int weight;
};
struct Person *Person_create(char *name, int age, int height, int weight)
{
struct Person *who = malloc(sizeof(struct Person));
assert(who != NULL);
who->name = strdup(name);
who->age = age;
who->height = height;
who->weight = weight;
return who;
}
void Person_destroy(struct Person *who)
{
assert(who != NULL);
free(who->name);
free(who);
}
void Person_print(struct P
超级会员免费看
订阅专栏 解锁全文
73

被折叠的 条评论
为什么被折叠?



