70,022
社区成员




#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct STUTAG
{
int age;
char name[100];
char addr[40];
}STU;
int main()
{
STU* pt1 = (STU*)malloc(sizeof(STU)*2);
//通过方式一赋值
if(pt1 != NULL)
{
pt1[0].age = 10;
strcpy(pt1[0].name,"this is test");
pt1[1].age = 20;
strcpy(pt1[1].name,"this is xxxtest");
}
//通过方式2赋值
/*
if(pt1 != NULL)
{
pt1->age = 10;
strcpy(pt1->name,"this is test");
pt1 ++;
pt1->age = 10;
strcpy(pt1->name,"this is testnsn");
pt1--;
}
*/
STU** pt2 = (STU**)malloc(sizeof(STU*)*2);
pt2[0] = pt1;
pt1++;
pt2[1] = pt1;
pt1--;
printf("pt2[0]: pt2[0]->name %s\n", pt2[0]->name);
printf("pt2[1]: pt2[1]->name %s\n", pt2[1]->name);
free(pt1);
//到底如何释放pt2呢?我们项目里面都是free(&pt2)使用,但是我测试发现会出core,这样释放返回没有问题free(&pt2[0]),不得期解,望各位高手指教
//free(&pt2)/free(&pt2[0]);
return 0;
STU* pt11 = (STU*)malloc(sizeof(STU)*2);
STU* pt12 = (STU*)malloc(sizeof(STU)*2);
pt2[0] = pt11;
pt2[1] = pt12;
int i = 0;
for(i=0 ; i< 2; i ++)
{
//通过pt2去释放pt11和pt12的内存空间,如下方式等同于free(pt11)和free(pt12)
free(pt2[i]);
}
free(pt2);
for(i = 0; i < 2; i++)
free(pt2[i]);
free(pt2);