结构体数组
#include<stdio.h>
struct student
{char name[20];int age;int scores[3];char addr[50];
};
int main()
{struct student stu={"林冲",30,100,100,100,"汴京"};struct student* p;p=&stu;//printf("%s\n",(*p).name);//printf("%d\n",(*p).age);//结构体指针->成员//结构体变量.成员 printf("%s\n",p->name);printf("%d\n",p->age);printf("%d\n",p->scores[0]);printf("%d\n",p->scores[1]);printf("%d\n",p->scores[2]);printf("%s\n",p->addr);return 0;
}
结构体指针:
先申请结构体大小的内存,在分别对结构体中指针类型申请对应的内存
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct student stu;
//结构体为指针类型
struct student
{char* name;int age;int* score;char* addr;
};
int main()
{//通过结构体指针操作堆空间stu* p=(stu*)malloc(sizeof(stu)*3);for(int i=0;i<3;i++){//(p + i)->name;p[i].name=(char*)malloc(sizeof(char*)*10);p[i].score=(int*)malloc(sizeof(int*)*3);p[i].addr=(char*)malloc(sizeof(char*)*50);}for(int i=0;i<3;i++)scanf("%s %d %d %d %d %s",p[i].name,&p[i].age,&p[i].score[0],&p[i].score[1],&p[i].score[2],p[i].addr);printf("************************\n");for(int i=0;i<3;i++){printf("%s ",p[i].name);printf("%d ",p[i].age);printf("%d ",p[i].score[0]);printf("%d ",(p+i)->score[1]);printf("%d ",(p+i)->score[2]);printf("%s \n",(p+i)->addr);}//释放堆空间for(int i=0;i<3;i++){free(p[i].name);free(p[i].score);free(p[i].addr);} free(p);return 0;
}