MST

星途 面试题库

面试题:C语言计算不规则多维数组长度

在C语言中,定义一个不规则二维数组 int *arr[] = { (int[]){1, 2}, (int[]){3, 4, 5}, (int[]){6} }; 请编写函数来自动计算每一行的元素个数,并返回一个包含每行元素个数的新数组,最后在主函数中调用该函数并输出结果。
48.6万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>

// 函数声明
int* countElementsPerRow(int *arr[], int rows);

int main() {
    int *arr[] = { (int[]){1, 2}, (int[]){3, 4, 5}, (int[]){6} };
    int rows = sizeof(arr) / sizeof(arr[0]);
    int *result = countElementsPerRow(arr, rows);

    for (int i = 0; i < rows; i++) {
        printf("第 %d 行元素个数: %d\n", i + 1, result[i]);
    }
    free(result);
    return 0;
}

int* countElementsPerRow(int *arr[], int rows) {
    int *count = (int*)malloc(rows * sizeof(int));
    if (count == NULL) {
        perror("内存分配失败");
        exit(EXIT_FAILURE);
    }

    for (int i = 0; i < rows; i++) {
        int *row = arr[i];
        int j = 0;
        while (row[j] != '\0') {
            j++;
        }
        count[i] = j;
    }

    return count;
}

上述代码中:

  1. countElementsPerRow 函数用于计算每一行的元素个数,并返回一个包含每行元素个数的数组。
  2. main 函数中,首先定义了不规则二维数组 arr,然后调用 countElementsPerRow 函数获取每行元素个数的数组,并输出结果。最后释放动态分配的内存。