综述
该章节主要是记录指针(地址)的一些使用,主要来源于自己生活中遇到的问题,在此记录。
目录
- 不同数据结构数据的访问
不同数据结构数据的访问
场景描述
我有一个数据保存用户信息的数据结构,如果使用char * 接收了保存用户信息的内存的地址,还可以将这块空间指为用户信息结构的空间吗?
模型代码
模型代码使用char *指向的地址,去访问得到了用户的所有信息,这是在知道用户结构体名称的前提下,如果不知道用户的结构体类型呢?只知道用户的结构体数据有哪些,又应该怎么访问用户的信息?
#include <stdio.h>
#include <stdlib.h>
#define bool char
#define true 1
#define false 0
#define NAME_LEN 20
#define OCCPUTION_LEN 10
#define LOCATION_LEN 50
typedef struct USER_DESC{ //用户信息结构
char *pcName;
bool bSex;
unsigned int uiAge;
char *pcOccupation;
char *pcLocation;
}USER_DESC_S;
typedef struct USER{
int iID; //用户身份标识符
USER_DESC_S *pstUserInfo; //用户信息结构存储地址
}USER_S;
int main(int argc, char *argv){
char *pcTemp = NULL;
USER_S *pstUser = NULL;
pcTemp = malloc(sizeof(USER_S));
memset(pcTemp , 0x0, sizeof(USER_S));
//初始化用户身份标识
((USER_S *)pcTemp)->iID = 1296968;
pstUser = pcTemp;
pstUser->pstUserInfo = malloc(sizeof(USER_DESC_S));
memset(pstUser->pstUserInfo, 0x0, sizeof(USER_DESC_S));
pstUser->pstUserInfo->pcName = malloc(sizeof(char) * NAME_LEN);
pstUser->pstUserInfo->pcOccupation = malloc(sizeof(char) * OCCPUTION_LEN);
pstUser->pstUserInfo->pcLocation = malloc(sizeof(char) * LOCATION_LEN);
memset(pstUser->pstUserInfo->pcName, 0x0, sizeof(char) * NAME_LEN);
memset(pstUser->pstUserInfo->pcOccupation, 0x0, sizeof(char) * OCCPUTION_LEN);
memset(pstUser->pstUserInfo->pcLocation, 0x0, sizeof(char) * LOCATION_LEN);
//初始化用户具体信息
snprintf(pstUser->pstUserInfo->pcName, sizeof(char) * NAME_LEN, "SlowFei");
pstUser->pstUserInfo->bSex = true;
pstUser->pstUserInfo->uiAge = 25;
snprintf(pstUser->pstUserInfo->pcOccupation, sizeof(char) * OCCPUTION_LEN, "TC");
snprintf(pstUser->pstUserInfo->pcLocation, sizeof(char) * LOCATION_LEN, "HangZhou-ZEJIANG");
//使用pcTemp指向的地址输出用户数据
printf("user id: %d\n", ((USER_S *)pcTemp)->iID);
printf("user name: %s\n", ((USER_S *)pcTemp)->pstUserInfo->pcName);
printf("user sex: %d\n", ((USER_S *)pcTemp)->pstUserInfo->bSex);
printf("user age: %d\n", ((USER_S *)pcTemp)->pstUserInfo->uiAge);
printf("user occupation: %s\n", ((USER_S *)pcTemp)->pstUserInfo->pcOccupation);
printf("user locatioin: %s\n", ((USER_S *)pcTemp)->pstUserInfo->pcLocation);
free(pstUser->pstUserInfo->pcName);
pstUser->pstUserInfo->pcName = NULL;
free(pstUser->pstUserInfo->pcOccupation);
pstUser->pstUserInfo->pcOccupation = NULL;
free(pstUser->pstUserInfo->pcLocation);
pstUser->pstUserInfo->pcLocation = NULL;
free(pstUser->pstUserInfo);
pstUser->pstUserInfo = NULL;
free(pstUser);
pstUser = NULL;
return 0;
}
浙公网安备 33010602011771号