您的位置:首页 > 其它

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

2017-12-14 20:04 155 查看
#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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  动态分配 struct