动态分配数组

来源:互联网 发布:淘宝达人帖子要求 编辑:程序博客网 时间:2024/05/20 20:18


#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相当于 &t[0]   t + i 相当于&t[i] *t[i] 就相当于t所指向地址的内容 内容是个指针,通过.指向结构体内容。      
      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]); //指向结构体的指针
        }
    }
    free(t); // 指向数组指针的指针。
    return 0;
}


原创粉丝点击