学习网址

C语言动态内存函数(malloc、calloc、realloc、free)详解:https://www.jb51.net/program/295325hjh.htm

C语言动态内存函数详解:https://www.jb51.net/article/223725.htm

malloc函数-申请结构体类型的空间

我们也可以给一个结构体开辟动态空间

假设结构体名为student

student         *ptr = (student *)malloc(sizeof(student));
struct student *ptr1 = (struct student *)malloc(sizeof(struct student));

C语言-malloc学习_stdib

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int num = 0;
    printf("请输入你要申请的空间大小(int类型):");scanf("%d", &num);
	int* ptr = NULL;
    ptr = (int*)malloc(num);
    struct student {	   // 结构体各个变量的大小: 
	    char name[50];	   // 50
	    int age;		   // 4
	    float score;	   // 4
 		unsigned int sex;  // 6
	};					   // 共64 
	typedef struct student Student; // 使用typedef为结构体类型定义别名,没使用别名就要定义时前面加上struct 
    struct student *ptr1 = (struct student *)malloc(sizeof(struct student));
    Student        *ptr2 = (struct student *)malloc(sizeof(struct student));
    // sizeof(Student)是计算结构体的大小,单位字节。返回结构体中所有成员变量所占用的内存空间总和。整数类型的数据。 
    printf("Student的长度为%d\n",sizeof(Student)); 
	printf("ptr1的长度为%d\n",sizeof(*ptr1)); 	
	   
    // 程序的最后注意将申请的空间释放--free()
    free(ptr);  //释放ptr指向的空间
    free(ptr1);
    free(ptr2);
    ptr  = NULL;//让ptr指向空
    ptr1 = NULL;
    ptr2 = NULL;
	return 0; 
}