MST

星途 面试题库

面试题:C语言数组元素访问技巧之专家难度

在C语言中,使用变长数组(VLA)定义一个三维数组 `int arr[n][m][k];`(假设 `n`, `m`, `k` 已正确定义),编写一个函数,实现对这个三维数组进行螺旋式遍历(类似螺旋矩阵的遍历方式),并将遍历结果存储到一个一维数组中返回。请详细描述你的思路,并写出实现代码。注意处理边界条件和内存管理。
38.7万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
  1. 思路描述

    • 螺旋式遍历三维数组可以类比螺旋矩阵遍历的思路。我们可以通过模拟螺旋的路径来遍历三维数组。
    • 定义六个变量分别表示当前遍历的边界:leftrighttopbottomfrontback,分别对应数组在不同维度的边界。
    • 按照螺旋的方向,依次从左到右、从上到下、从右到左、从下到上,在不同的面(三维的不同层面)上进行遍历。每次遍历完一个面,更新边界值,然后进入下一个层面继续遍历。
    • 遍历过程中,将数组元素依次存入一维数组中。
    • 注意在遍历过程中,当遍历完一个层面,要检查是否所有元素都已遍历完,如果是则结束遍历。
  2. 代码实现

#include <stdio.h>
#include <stdlib.h>

// 函数声明
int* spiralTraversal(int n, int m, int k, int arr[n][m][k]);

int main() {
    int n = 2, m = 2, k = 2;
    int arr[2][2][2] = {
        {
            {1, 2},
            {3, 4}
        },
        {
            {5, 6},
            {7, 8}
        }
    };
    int *result = spiralTraversal(n, m, k, arr);
    for (int i = 0; i < n * m * k; i++) {
        printf("%d ", result[i]);
    }
    free(result);
    return 0;
}

int* spiralTraversal(int n, int m, int k, int arr[n][m][k]) {
    int *result = (int*)malloc(n * m * k * sizeof(int));
    if (result == NULL) {
        perror("malloc");
        return NULL;
    }
    int left = 0, right = m - 1, top = 0, bottom = n - 1, front = 0, back = k - 1;
    int index = 0;
    while (left <= right && top <= bottom && front <= back) {
        // 从左到右遍历front面
        for (int i = left; i <= right; i++) {
            result[index++] = arr[top][i][front];
        }
        top++;
        if (top > bottom) break;
        // 从上到下遍历right面
        for (int i = top; i <= bottom; i++) {
            result[index++] = arr[i][right][front];
        }
        right--;
        if (left > right) break;
        // 从右到左遍历back面
        for (int i = right; i >= left; i--) {
            result[index++] = arr[bottom][i][back];
        }
        bottom--;
        if (top > bottom) break;
        // 从下到上遍历left面
        for (int i = bottom; i >= top; i--) {
            result[index++] = arr[i][left][back];
        }
        left++;
        front++;
        back--;
    }
    return result;
}
  1. 边界条件和内存管理
    • 边界条件
      • 在每次遍历完一个方向后,检查是否已经遍历完某一维的所有元素,如果是则及时结束遍历,避免越界访问。例如在每次改变topbottomleftrightfrontback的值后,都检查相应的边界条件,防止数组越界。
    • 内存管理
      • 使用malloc为存储螺旋遍历结果的一维数组分配内存,并在函数返回前检查malloc是否成功。如果malloc失败,使用perror输出错误信息并返回NULL
      • 在调用函数的地方,在使用完返回的数组后,使用free释放内存,避免内存泄漏。