#include <stdio.h>
#include <stdlib.h>
typedef struct student
{
int age;
int sex;
}stu;
typedef struct classroom
{
int num;
stu **people;
}class;
int main()
{
//定义临时变量 tmp
stu * tmp = NULL;
//定义班级
class senior;
//班级人数
senior.num = 10;
class *grade =&senior;
tmp = malloc(senior.num * sizeof(stu));
printf("malloc memory address is %p\n",tmp);
printf("sizeof(int) is %d\n",sizeof(int));
printf("sizeof(senior) is %d\n",sizeof(senior));
printf("sizeof(stu) is %d\n",sizeof(stu));
tmp[0].age = 20;
tmp[0].sex = 1;
tmp[1].age = 25;
tmp[1].sex = 0;
printf("people[0] age is %d\n",tmp[0].age);
printf("people[1] age is %d\n",tmp[1].age);
return 0;
}
我的疑问是想通过几种方式操作申请的那块内存( 10 个 stu 结构体类型),既能通过 tmp 操作,又能通过结构体 senior 或者结构体指针 grade 操作,可是尝试了多次发现有点不对,我已经在指针和二级指针中迷失了方向.
我的几点理解: 我在结构体 class 班级中定义关于 stu 的二级指针,方便通过 stu 的指针去操作和管理 stu,起初是用的一级指针,发现解决不了问题,现在用二级指针,对地址这部分存在疑问.
1
kmyzzy 2017-06-15 16:25:07 +08:00
用一级指针,senior.people = stu
|
2
kmyzzy 2017-06-15 16:25:43 +08:00
错了,是 senior.people = tmp
|
6
dingz 2017-06-15 16:54:21 +08:00
typedef struct classroom
{ int num; stu people[0]; }class; class *grade = (class *)malloc(sizeof(class) + sizeof(stu) * 10); grade->num = 10; |
7
dingz 2017-06-15 16:56:16 +08:00
grade->people[0].age = 20;
grade->people[0].sex = 1; grade->people[1].age = 25; grade->people[1].sex = 0; |