可以在C的二维阵列没有明确大小初始化? [英] Can a two-dimensional array in C be initialized without explicit size?

查看:99
本文介绍了可以在C的二维阵列没有明确大小初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于在C.二维数组我现在才知道(直接编译经验)的问题,我不能初始化类似这样的数组一维数组是这样的:

I have a question regarding two-dimensional arrays in C. I know now (from direct compiler experience) that I can't initialize such an array analogously to one-dimensional arrays like this:

int multi_array[][] = {
  {1,2,3,4,5},
  {10,20,30,40,50},
  {100,200,300,400,500}
};

> compiler output:

gcc -o arrays arrays.c
arrays.c: In function ‘main’:
arrays.c:8:9: error: array type has incomplete element type

这工作最接近的解决方案是,明确规定列数是这样的:

The closest solution that works is to provide the number of columns explicitly like this:

int multi_array[][5] = {
  {1,2,3,4,5},
  {10,20,30,40,50},
  {100,200,300,400,500}
};

我的问题是:能不能做到整齐的没有的明确(所有编译后应该能够推断本身)提供的数字?我不是在谈论与的malloc 或某事,而是一些接近手动构造它是我的尝试。
此外,有人可以博学关于C编译器从低层次的角度解释了为什么我的初步尝试不起作用?

My question is: can it be done neatly without supplying the number explicitly (which after all the compiler should be able to infer itself)? I'm not talking about manually constructing it with malloc or something but rather something close to what I tried. Also, can someone knowledgeable about C compilers explain from a low-level perspective why my initial attempt does not work?

我用普通的 GCC 无非标准选项编译code。

I used plain gcc with no non-standard options to compile the code.

感谢

推荐答案

您可以使用C99复合文字的功能做到这一点。

You can do this using the C99 compound literal feature.

一个部分的想法是一个初始化列表的长度可以这样确定:

A partial idea is that the length of an initializer list can be determined like this:

sizeof (int[]){ 1, 2, 3, 4, 5 } / sizeof(int)

我们需要的是,你可以通过包含逗号的宏参数的唯一方法就是把周围的括号一种解决方法(的一部分)的说法:

We need a workaround for the fact that the only way you can pass an argument containing a comma to a macro is to put parentheses around (part of) the argument:

#define ROW(...) { __VA_ARGS__ }

然后下面的宏从第一行推导出第二尺寸:

Then the following macro deduces the second dimension from the first row:

#define MAGIC_2DARRAY(type, ident, row1, ...) \
        type ident[][sizeof (type[])row1 / sizeof (type)] = { \
                row1, __VA_ARGS__ \
        }

有仅在有至少两行的工作原理。

It only works if there are at least two rows.

例如:

MAGIC_2DARRAY(int, arr, ROW(7, 8, 9), ROW(4, 5, 6));

您可能不希望在一个真正的程序中使用,但它是可能的。

You probably do not want to use this in a real program, but it is possible.

有关通过这种阵列功能,C99的可变长度阵列功能是有用的,像一个函数:

For passing this kind of array to functions, the C99 variable length array feature is useful, with a function like:

void printarr(int rows, int columns, int array[rows][columns]) { ... }

称为:

printarr(sizeof arr / sizeof arr[0], sizeof arr[0] / sizeof arr[0][0], arr);

这篇关于可以在C的二维阵列没有明确大小初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆