[C语言结构体内存管理: 动态内存分配]
在C语言中,一个结构体占用的内存空间是由其成员变量决定的。有时候,我们需要在程序运行时动态地分配内存空间给结构体,这就需要用到动态内存分配。
动态内存分配的函数是malloc,其原型为:
void* malloc(size_t size);
该函数返回一个void类型的指针,指向新分配的内存块的起始地址。参数size表示需要分配的内存空间大小,单位是字节。
下面是一个例子,演示了如何使用malloc函数动态分配内存空间给结构体:
#include <stdio.h>
#include <stdlib.h>
struct Student {
char name[20];
int age;
};
int main() {
struct Student *p;
p = (struct Student*) malloc(sizeof(struct Student));
if (p == NULL) {
printf("Memory allocation failed!\n");
exit(1);
}
strcpy(p->name, "John");
p->age = 18;
printf("Name: %s\n", p->name);
printf("Age: %d\n", p->age);
free(p);
return 0;
}
在上面的例子中,我们定义了一个结构体Student,包含了姓名和年龄两个成员变量。在main函数中,我们首先定义了一个Student类型的指针p,并将其初始化为空指针