c - K&R练习: Multidimensional array into pointer array

标签 c multidimensional-array kernighan-and-ritchie

练习(5-9): 用指针而不是索引重写例程 day_of_year

static char daytab[2][13] = {
    {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};

/* day_of_year: set day of year from month and day */
int day_of_year(int year, int month, int day)
{
    int i, leap;

    leap = (year%4 == 0) && (year%100 != 0) || (year%400 == 0);
    for (i = 1; i < month; i++)
    {
        day += daytab[leap][i];
    }

    return day;
}

我可能只是累了,没有思考,但实际上如何创建一个带指针的多维数组?

我可能会弄清楚函数的其余部分,但语法不正确。

最佳答案

您只是被要求修改 day_of_year 例程,而不是 daytab 声明。我会按原样保留该数组,并按如下方式修改 day_of_year:

/* day_of_year: set day of year from month and day */
int day_of_year(int year, int month, int day)
{
    char* p = (year%4 == 0) && (year%100 != 0) || (year%400 == 0) ? 
        daytab[0] : daytab[1];

    p++;
    for (i = 1; i < month; i++, p++)
    {
        day += *p;
    }

    return day;
}

如果你想让p的声明更短,你可以这样做:

    char* p = daytab[(year%4 == 0) && (year%100 != 0) || (year%400 == 0)];

如果您还想删除该访问权限:

    char* p = *(daytab + ((year%4 == 0) && (year%100 != 0) || (year%400 == 0)));

有人可能会争辩说它看起来很丑,但是嘿,这就是你用指针得到的结果。

关于c - K&R练习: Multidimensional array into pointer array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/485940/

相关文章:

c++ - 二维数组中的最后一个空格;矩阵

c - 函数声明与原型(prototype)的替代 (K&R) C 语法

c - (K&R) 内部名称至少前 31 个字符是重要的?

c - 什么是 ubuntu 中的 EOF 以及 Kernighan 和 Ritchie

比较字符

C : 0 & 1 combinations using recursion

c - C语言中如何获取两个日期之间的时间间隔

C scanf 意外地使用 %i 扫描日期

php - 无法将新字段添加到 foreach 中的数组

php - 在两个 csv 文件之间用 PHP 实现左连接