MST

星途 面试题库

面试题:C语言联合体在异构协议解析及内存优化中的应用

在一个异构网络环境中,存在多种不同格式的设备状态报告协议。每个协议报告的基础结构类似,但数据部分根据设备类型不同而不同,可能是固定长度数组、变长字符串或者自定义结构体,并且需要尽可能优化内存使用。使用C语言联合体设计一个通用的数据结构来解析这些异构协议,并编写函数实现高效的协议识别与数据解析,同时阐述如何通过联合体的特性优化内存使用。
30.2万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

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根据设备类型不同,可能存储FixedArrayDataVariableStringDataCustomStructData。由于它们不会同时使用,所以通过联合体可以避免为每种数据类型单独分配内存,从而优化内存使用。例如,如果使用结构体,每种数据类型都需要占用独立的内存空间,而联合体只需要为最大的数据类型分配内存,其他数据类型复用这块内存,在异构网络环境中处理多种不同格式数据时,有效减少了内存的浪费。