面试题答案
一键面试1. 设计通用数据结构
#include <stdio.h>
#include <string.h>
// 定义不同类型的数据
typedef struct {
int fixedArray[10];
} FixedArrayData;
typedef struct {
char variableString[100];
} VariableStringData;
typedef struct {
int id;
float value;
} CustomStructData;
// 通用联合体
union DeviceData {
FixedArrayData fixed;
VariableStringData variable;
CustomStructData custom;
};
// 协议类型枚举
typedef enum {
PROTOCOL_FIXED_ARRAY,
PROTOCOL_VARIABLE_STRING,
PROTOCOL_CUSTOM_STRUCT
} ProtocolType;
// 通用设备状态报告结构体
typedef struct {
ProtocolType type;
union DeviceData data;
} DeviceStatusReport;
2. 协议识别与数据解析函数
// 解析固定长度数组协议
void parseFixedArray(const char* buffer, DeviceStatusReport* report) {
report->type = PROTOCOL_FIXED_ARRAY;
for (int i = 0; i < 10; i++) {
report->data.fixed.fixedArray[i] = *((int*)(buffer + i * sizeof(int)));
}
}
// 解析变长字符串协议
void parseVariableString(const char* buffer, DeviceStatusReport* report) {
report->type = PROTOCOL_VARIABLE_STRING;
strcpy(report->data.variable.variableString, buffer);
}
// 解析自定义结构体协议
void parseCustomStruct(const char* buffer, DeviceStatusReport* report) {
report->type = PROTOCOL_CUSTOM_STRUCT;
report->data.custom.id = *((int*)buffer);
report->data.custom.value = *((float*)(buffer + sizeof(int)));
}
// 通用的协议识别与数据解析函数
void parseProtocol(const char* buffer, int bufferSize, DeviceStatusReport* report) {
// 简单示例,根据bufferSize来识别协议
if (bufferSize == sizeof(FixedArrayData)) {
parseFixedArray(buffer, report);
} else if (bufferSize <= sizeof(VariableStringData)) {
parseVariableString(buffer, report);
} else if (bufferSize == sizeof(CustomStructData)) {
parseCustomStruct(buffer, report);
} else {
// 未知协议处理
report->type = (ProtocolType)-1;
}
}
3. 联合体特性优化内存使用阐述
联合体的特性是所有成员共享同一块内存空间,其大小为最大成员的大小。在这个场景中,union DeviceData
根据设备类型不同,可能存储FixedArrayData
、VariableStringData
或CustomStructData
。由于它们不会同时使用,所以通过联合体可以避免为每种数据类型单独分配内存,从而优化内存使用。例如,如果使用结构体,每种数据类型都需要占用独立的内存空间,而联合体只需要为最大的数据类型分配内存,其他数据类型复用这块内存,在异构网络环境中处理多种不同格式数据时,有效减少了内存的浪费。