01 栈区 堆区 结构体数组
#include <stdlib.h>
#include <stdio.h>
typedef struct persons
{
char name[21];
int age;
}persons;
void main() {
persons psn[3] = { {"何无忌",33}, {"刘毅",34},{"檀凭之",45} };
for (int i = 0; i < 3; i++)
{
printf("%s\t%d\n", psn[i].name, psn[i].age);
}
printf("\n");
//**************************************************************
persons* ppsn = (persons*)malloc(sizeof(persons) * 3);
for (int i = 0; i < 3; i++)
{
strcpy(ppsn[i].name,"魏咏之") ;
ppsn[i].age =40+i;
}
for (int i = 0; i < 3; i++)
{
printf("%s\t%d\n", ppsn[i].name, ppsn[i].age);
}
if(ppsn!=NULL)//free两次会报错,所以判断一下
{
free(ppsn);
ppsn = NULL;
}
system("pause");
}
//动态空间,堆区开辟空间,栈区指针指向堆区
02 结构体动态数组的内存分布
char name[21];内存对齐24=4*6>21,int 4,persons 24+4=28,连续分布
#include <stdlib.h>
#include <stdio.h>
typedef struct persons
{
char name[21];
int age;
}persons;
void main() {
persons* ppsn = (persons*)malloc(sizeof(persons) * 3);
for (int i = 0; i < 3; i++)
{
printf("%p\t%p\n", ppsn[i].name, &ppsn[i].age);
}
if (ppsn != NULL)//free两次会报错,所以判断一下
{
free(ppsn);
ppsn = NULL;
}
system("pause");
}
//动态空间,堆区开辟空间,栈区指针指向