今天需要用到一个双指针,不太熟悉其使用方法,网上没找到合适的事例,于是自己尝试写一个。只要理解了指针的含义,还是不难。
代码全部如下:
#include "stdafx.h"
#include <stdlib.h>
#include <memory.h>
#include <string.h>
//定义结构体
typedef struct tagUSERCLASSTYPE
{
char szName[32];
char szID[18];
int szAge;
} User_t, *UserPtr_t;
int main(int argc, char* argv[])
{
User_t **pp = (User_t**)malloc(sizeof(User_t*) * 2);
User_t **tmp;
tmp = pp;
for (int i=0; i<2; i++)
{
(*tmp) = (User_t*)malloc(sizeof(User_t));
tmp++;
}
tmp = pp;
strcpy((*tmp)->szName, "aaa");
strcpy((*tmp)->szID, "001");
(*tmp)->szAge = 10;
tmp++;
strcpy((*tmp)->szName, "bbb");
strcpy((*tmp)->szID, "002");
(*tmp)->szAge = 20;
tmp = pp;
for (i=0; i<2; i++)
{
printf("name: %s, id: %s, age: %d/r/n", (*tmp)->szName, (*tmp)->szID, (*tmp)->szAge);
tmp++;
}
//释放,注意释放次序
//先释放结构体指针所指向的内存
tmp = pp;
for (i=0; i<2; i++)
{
free(*tmp);
tmp++;
}
//再释放结构体指针数组的内存
for (i=0; i<2; i++)
{
free (*tmp);
tmp++;
}
pp = NULL;
tmp = NULL;
return 0;
}