MST

星途 面试题库

面试题:C语言联合体作为函数返回值在复杂数据处理中的应用

假设有一个结构体数组,结构体中有一个联合体成员,联合体包含一个int和一个char数组。编写一个函数,该函数接收这个结构体数组及其长度作为参数,通过对数组元素的处理,返回一个联合体,联合体成员根据处理结果选择赋值为int或char数组。请阐述你的设计思路并实现代码。
34.9万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 定义结构体和联合体,结构体包含联合体成员。
  2. 编写函数,接收结构体数组及其长度。
  3. 在函数内部,根据一定的处理逻辑(这里假设简单地根据数组第一个元素的某个条件来决定返回联合体的哪种类型),决定返回联合体中的 int 还是 char 数组。
  4. 进行相应的赋值操作并返回联合体。

代码实现

#include <stdio.h>
#include <string.h>

// 定义联合体
union MyUnion {
    int num;
    char str[10];
};

// 定义结构体
struct MyStruct {
    union MyUnion data;
};

// 处理函数
union MyUnion processArray(struct MyStruct arr[], int len) {
    union MyUnion result;
    if (len > 0 && strlen(arr[0].data.str) > 0) {
        // 假设根据第一个元素的char数组长度大于0,返回char数组
        strcpy(result.str, arr[0].data.str);
    } else {
        // 否则返回int
        result.num = 42;
    }
    return result;
}

int main() {
    struct MyStruct arr[2];
    strcpy(arr[0].data.str, "hello");
    arr[1].data.num = 10;

    union MyUnion res = processArray(arr, 2);
    if (strlen(res.str) > 0) {
        printf("Result string: %s\n", res.str);
    } else {
        printf("Result number: %d\n", res.num);
    }

    return 0;
}

在上述代码中:

  1. 首先定义了 MyUnion 联合体和包含该联合体的 MyStruct 结构体。
  2. processArray 函数接收结构体数组及其长度,根据第一个元素的 char 数组情况决定返回联合体的不同成员。
  3. main 函数中,初始化结构体数组并调用 processArray 函数,根据返回的联合体成员类型进行相应输出。

请注意,实际应用中处理逻辑应根据具体需求进行修改。