C - 我可以将函数参数列表中的多维数组的大小设置为高于其实际大小的值吗?

C - Can I set the size of a multidimensional array in a function parameter list to something higher than its actual size?

如您所知,在 C 函数声明中,您必须命名所有维度大小,但数组参数之一除外。我现在正在使用一个二维数组,其中两个大小都是在运行时生成的,但是我想将该数组传递给另一个函数来填充它。

我的想法是在函数声明中使用最大大小,如下所示:

int max_size = 100;
int actual_size;
int another_size;

static void fill_array(int ar[][max_size])
{
    for(int i = 0; i < another_size; i++)
    {
        for(int j = 0; j < actual_size; j++)
        {
            ar[i][j] = some int;
        }
    }
}

static void main()
{
    if(some_input) actual_size = 50;
    else actual_size = 100;

    if(some_input) another_size = 10;
    else another_size = 20;

    int empty_array[another_size][actual_size] = {0};
    fill_array(empty_array);
}

我的想法是,即使该函数可能认为每个数组行都有 100 个整数,但无论如何我们只填充前 50 个。这是不聪明吗?有什么办法可以做到同样更清洁吗? C 的新手,很抱歉,如果这是一个非常明显的事情。

对于初学者这样的函数 main

的声明
static void main()

不标准。

函数应该这样声明

int main( void )

如果您的编译器支持可变长度数组,那么您可以像这样声明函数

static void fill_array( size_t rows, size_t cols, int ar[][cols] );

并传递任意大小的二维数组。

这是一个演示程序。

#include <stdio.h>

static void fill_array( size_t rows, size_t cols, int a[][cols] )
{
    for ( size_t i = 0; i < rows; i++ )
    {
        for ( size_t j = 0; j < cols; j++ )
        {
            a[i][j] = i * cols + j;
        }
    }
}

int main(void) 
{
    size_t rows;
    size_t cols;

    printf( "Enter the number of rows: " );
    scanf( "%zu", &rows );

    printf( "Enter the number of columns: " );
    scanf( "%zu", &cols );

    int a[rows][cols];

    fill_array( rows, cols, a );

    for ( size_t i = 0; i < rows; i++ )
    {
        for ( size_t j = 0; j < cols; j++ )
        {
            printf( "%2d ", a[i][j] );
        }
        putchar( '\n' );
    }

    return 0;
}

其输出可能类似于

Enter the number of rows: 3
Enter the number of columns: 5
 0  1  2  3  4 
 5  6  7  8  9 
10 11 12 13 14 

如果您想在函数中将传递的数组用作 "normal" 数组,您可以使用此方法。即使与 ANSI C 一起工作。

https://godbolt.org/z/aiNjef

void fillarray(void *arr, int cols, int rows)
{
    int (*newarr)[cols] = arr;

    for(int row = 0; row < rows; row++)
    {
        for(int col = 0; col < cols; col++)
        {
            newarr[row][col] = (row << 4) | (col);
        }
    }
}

#define ROWS    5
#define COLS    10

int main(void)
{
    int arr[ROWS][COLS];

    fillarray(arr, COLS, ROWS);
    for(int row = 0; row < ROWS; row++)
    {
        for(int col = 0; col < COLS; col++)
        {
            printf("%02x ", arr[row][col]);
        }
        printf("\n");
    }
}