Aku*_*udo 5 c arrays pointers return-type
我一直在尝试将程序从Java转换为C,它是手表的模拟器,并显示我使用Ascii艺术的时间.我已将所有数字(0-9)存储在2D字符数组(fx.9)中:
char nine[7][5] = {
{ '0', '0', '0', '0' },
{ '0', ' ', ' ', '0' },
{ '0', ' ', ' ', '0' },
{ '0', '0', '0', '0' },
{ ' ', ' ', ' ', '0' },
{ ' ', ' ', ' ', '0' },
{ ' ', ' ', ' ', '0' }
};
Run Code Online (Sandbox Code Playgroud)
我现在有一个函数,其作用是转换存储在int数组中的时间(fx.22:04:59,将在数组中存储为220459).该函数应该将相应的Ascii art返回给每个数字,这样我最终可以调用打印时间(以ascii形式)的函数,该函数需要6个char [] []参数.
所以简而言之,我需要知道调用此函数的6个参数:
void printScreen(char hourFirstDigit[7][5], char hourSecondDigit[7][5], char minuteFirstDigit[7][5], char minuteSecondDigit[7][5], char secFirstDigit[7][5], char secSecondDigit[7][5])
Run Code Online (Sandbox Code Playgroud)
在java中我的解决方案只是创建一个返回char [] []数组的函数,然后是10个案例(0-9)的switch语句,(这里是前几行):
char timeToAsciiArt[][](int digitNumber, int small) {
switch (timeRightNow[digitNumber]) {
case 0:
return zero;
}
Run Code Online (Sandbox Code Playgroud)
可能的解决方案:我已经读过那里至少有两个可能解决问题的方法(一般来说),1.用指向数组的指针替换.2.用结构包装.
我的想法:1.我真的不确定如何返回指向数组的指针(有人可以用案例0来解释如何做到这一点:作为一个例子吗?:)
我建议采用以下方法。
定义一个函数,其中包含具有静态存储持续时间的图像数组。
例如
char ( * )[7][5] get_image( size_t i )
{
static char images[10][7][5] =
{
//...
{
{ '0', '0', '0', '0' },
{ '0', ' ', ' ', '0' },
{ '0', ' ', ' ', '0' },
{ '0', '0', '0', '0' },
{ ' ', ' ', ' ', '0' },
{ ' ', ' ', ' ', '0' },
{ ' ', ' ', ' ', '0' }
}
};
const size_t N = sizeof( images ) / sizeof( *images );
return i < N ? images[i] : NULL;
}
Run Code Online (Sandbox Code Playgroud)
或者如果函数有返回类型也许会更好char ( * )[5]
例如
char ( * )[5] get_image( size_t i )
{
static char images[10][7][5] =
{
//...
{
{ '0', '0', '0', '0' },
{ '0', ' ', ' ', '0' },
{ '0', ' ', ' ', '0' },
{ '0', '0', '0', '0' },
{ ' ', ' ', ' ', '0' },
{ ' ', ' ', ' ', '0' },
{ ' ', ' ', ' ', '0' }
}
};
const size_t N = sizeof( images ) / sizeof( *images );
return i < N ? images[i][0] : NULL;
}
Run Code Online (Sandbox Code Playgroud)
然后编写一个函数,该函数将在结构中返回一个包含 6 个元素和相应数字的数组。这些元素将作为调用 function 的参数get_image。
足够了。