C 中编译时具有未知维数和未知大小维度的数组

问题描述 投票:0回答:1

我必须使用在编译时未知维数和每个维大小的数组。 我写这段代码是为了做一些尝试:

#include<stdio.h>

int main() {

  int array_dim_size[16];
  int dim_nb=0;
  int coord[16];
  
  // Enter dimension sizes
  while (dim_nb<16 && scanf("%d",&array_dim_size[dim_nb]) && array_dim_size[dim_nb]!=0) dim_nb++;
  
  // array_dim_factor used to convert x dim coord to 1D dim coord
  int array_dim_factor[dim_nb];
  array_dim_factor[0]=1;
  for (int i=1; i<dim_nb; i++) array_dim_factor[i]=array_dim_factor[i-1]*array_dim_size[i-1];
  
  // Enter coordinates (no ckeck done because it is a very simple example)
  for (int i=0; i<dim_nb; i++) scanf("%d",&coord[i]);

  // Conversion from x dim coord to 1D dim coord
  int coord1D;
  coord1D=0;
  for (int i=0; i<dim_nb; i++) coord1D += array_dim_factor[i] * coord[i];
  printf("%d\n",coord1D);
  
}

总结一下,

  1. 尺寸大小在运行时输入。
  2. x 维度坐标转换为 1D 维度。

我确信这不是正确的方法。我觉得这不是 C 语言的好习惯。

编写该程序的正确方法是什么?感谢您的回答。

c multidimensional-array
1个回答
0
投票

我会使用指向数组的指针

int allocate(size_t zrows,size_t rows, size_t cols, int (**array)[rows][cols])
{
    *array = malloc(zrows * sizeof(**array));
    return !!(*array);
}

int randomize(size_t zrows,size_t rows, size_t cols, int (*array)[rows][cols])
{
    for(size_t z = 0; z < zrows; z++)
        for(size_t row = 0; row < rows; row++)
            for(size_t col = 0; col < cols; col++)
                array[z][row][col] = rand() % 1000;
}

int printarray(size_t zrows,size_t rows, size_t cols, int (*array)[rows][cols])
{
    for(size_t z = 0; z < zrows; z++)
    {
        for(size_t row = 0; row < rows; row++)
        {
            for(size_t col = 0; col < cols; col++)
            {
                printf("%5d ", array[z][row][col]);
            }
            printf("\n");
        }
        printf("\n\n");
    }
}

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


    srand(time(NULL));
    z = rand() % 10 + 2;
    rows = rand() % 6 + 1;
    cols = rand() % 8 + 1;
    int (*array)[rows][cols];

    printf("[%zu][%zu][%zu]\n", z, rows, cols);

    allocate(z, rows, cols, &array);
    if(array) 
    {
        randomize(z, rows, cols, array);
        printarray(z, rows, cols, array);
    }
    free(array);
}

https://godbolt.org/z/cT1bEqzcM

© www.soinside.com 2019 - 2024. All rights reserved.