gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:09:53 26 4
gpt4 key购买 nike

练习(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com