【发布时间】:2018-04-03 14:37:20
【问题描述】:
我是 C 的新手,我需要一个结构来传递常量二维数组以作为一个参数。我想做这个
const int a_size_x = 20;
const int a_size_y = 30;
const int a_output_array[size_x][size_y] = {{..., ...}, ..., {..., ...}};
const int b_size_x = 20;
const int b_size_y = 30;
const int b_output_array[size_x][size_y] = {{..., ...}, ..., {..., ...}};
void function(const int array[], int arr_size_x, int arr_size_y){
for (int i = 0; i < arr_size_x; i++)
{
for (int j = 0; j < arr_size_y; j++)
{
printf("%i ", array[i][j];
}
printf("\n");
}
function(a_output_array, a_size_x, a_size_y);
function(b_output_array, b_size_x, b_size_y);
更容易像这样调用 function(a):
const struct OUTPUT
{
const int size_x;
const int size_y;
const int array[size_x][size_y];
};
struct OUTPUT a = {.size_x = 20, .size_y = 30, .array = {{...}, ..., {...}};
....
struct OUTPUT z = {.size_x = 30, .size_y = 20, .array = {{...}, ..., {...}};
function(const struct OUTPUT out){
for (int i = 0; i < out.size_x; i++)
{
for (int j = 0; j < out.size_y; j++)
{
printf("%i ", out.array[i][j];
}
printf("\n");
}
function(a);
function(b);
但是编译器当然会说 size_x 和 size_y 在结构声明中是未声明的。
我读过关于灵活数组成员的文章,但是需要动态内存分配,并且在 AVR 哈佛架构中,malloc 不能在程序内存中工作,我将所有这些数据都放在那里。
在 C 中有什么方法可以做到吗?可能是,在 C++ 中?
UPDATE 对我有用的答案 - 创建一个长度为 2 + width*height 的一维数组,其中前两个成员是真实的宽度和高度并使用指针与此合作。这是一个打印出这个数组的示例函数:
char arr [11] =
{
3 // width
3 // height
1, 2, 3,
4, 5, 6,
7, 8, 9
}
void print_array(char *ptr)
{
char width = *ptr++;
char height= *ptr++;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
print("%c\t", *ptr++);
}
print("\n");
}
}
print_array(arr);
【问题讨论】:
-
这个
void function(const int array[], ...将数组定义为指向int的指针。所以这个printf("%i ", array[i][j];不会编译。将二维数组传递给它会调用未定义的行为,不说是完全错误的。 -
什么是
const struct OUTPUT?您需要一个或多个标签的列表 -
是的,sn-ps肯定有一些错误。实际上,当我编写函数时,我使用了
(int *array, int size_x, int size_y)参数。但这不是一个问题。我的问题是得到一个结构,它可以更容易地定义许多具有不同维度的对象和只需要一个参数(这个结构)来处理这些数组的函数,因为其中有许多'A_array','B_array'然后在具有所有三个参数的函数中多次调用它会使程序变得一团糟。