动态分配及对动态申请获得的结构体变量进行访问

来源:互联网 发布:站桩 知乎 编辑:程序博客网 时间:2024/05/20 04:48
#include <stdio.h>#include <stdlib.h>#include <malloc.h>typedef struct _student{    int num;    char name[30];} Student;Student s2[4];Student *s3[100]; Student **t;int main(){    int i, n;    scanf("%d", &n);    t = (Student **)malloc(n * sizeof(Student *));    for(i = 0; i < n; i ++)    {        //s3[i] = (Student *)malloc(sizeof(Student));        *(t + i) = (Student *)calloc(1, sizeof(Student));        if (t[i])        {            t[i]->num = (i + 1);            sprintf(t[i]->name, "Name%d", t[i]->num);        }    }    // s[0] .. s3[99]    // free pointer    for(i = 0; i < n; i ++)    {        if (t[i])        {            printf(" Student[i]: num=%d, name=%s\n", t[i]->num, t[i]->name);            free(t[i]);        }    }    return 0;}

malloc函数
void*malloc (int size)
void*malloc (n*sizeof(a))
无初始化
void free(void *p)释放空间

calloc函数
void* calloc (int items,int size);
void* calloc (n,sizeof(a));
此函数有初始化

*s[0].num = 100 等价于 s[0] -> num = 100;

阅读全文
0 0
原创粉丝点击